One UPDATE statement in an app I work on took 126 seconds to run, and every other write in the app waited behind it. I fixed it by changing one word: JOIN became CROSS JOIN. The same fix worked on another slow query. Then it turned out the one word had never been the real fix.
The app is a canvassing tool for a political campaign. Volunteers sign up for a list of addresses, knock on doors, and mark the list done. In campaign terms, that list of addresses is called a turf, which is why the queries below have names like van_turfs and turf_id.
The campaign keeps its voter data in a separate canvassing system. The app gets two separate feeds from that system’s API: the lists, with the people living at each list’s addresses, and a history of contacts, each recorded against a person. The app connects them by person, so to count the doors knocked on a list, it has to join the two itself. Those joins run over tables with millions of rows, and they’re the queries in this post.
The app runs on Fly.io and keeps everything in one Turso database, which is hosted SQLite you talk to over HTTPS. The whole setup, hosting and database together, cost less than $35 for October, when the campaign was in full swing. The trade-off of keeping everything in one SQLite database is that it runs one write at a time, so a slow write delays every other write in the app: sign-ins, volunteers signing up for lists, everything.
The Slow Update
The UPDATE records how many doors a volunteer knocked on each list they signed up for. To count them, it takes the list’s roster (the people living at its addresses) and looks each person up in a table of contacts, which holds the last time a volunteer knocked on that person’s door. Then it counts the doors with a contact during the time the volunteer had the list:
SELECT count(DISTINCT r.door_hash)
FROM van_turf_roster r
JOIN van_person_contacts c
ON c.campaign_id = ? AND c.person_hash = r.person_hash
WHERE r.turf_id = van_turf_checkouts.turf_id
AND c.last_in_person_at >= ?
AND c.last_in_person_at <= ?
The fast way to run this is to start from the roster for one list (a few hundred people) and look up each person’s contact by primary key. That’s a few hundred lookups per list.
Left to pick the join order, SQLite’s planner started from the contacts instead. It read every contact in the campaign, nearly 60,000 of them, for each list. It did that twice per list, because the count subquery appears twice in the UPDATE:
UPDATE van_turf_checkouts SET doors_knocked = (…count subquery…)
WHERE …
AND (doors_knocked IS NULL OR doors_knocked < (…count subquery…))
The first copy computes the new count. The second makes sure the count only goes up. The app keeps only each person’s most recent contact, so if another volunteer knocks the same door later, the earlier knock falls outside this volunteer’s time with the list, and a fresh count comes out lower. The second copy stops the count from dropping when that happens.
The results were correct. The planner’s order was reading tens of thousands of rows to find a few hundred.
Computing the count once and reusing it sounds simpler, but the usual ways to do that cost something else. Reading the counts into the app and writing them back takes two statements, so another write can land between the read and the write, and each one is a separate round trip over HTTPS. Computing the count once inside the SET with something like drops the check in the WHERE, so the UPDATE rewrites every row it looks at, including the ones whose count didn’t go up, and holds the write lock longer to do it. Repeating the subquery keeps the read and the write in one statement and writes only the rows whose count went up.
SQLite 3.33 and later has another option: UPDATE … FROM. It lets you compute each list’s count once in a subquery, join it to the rows being updated, and use it in both the SET and the check, all in one statement. It wouldn’t have fixed this query, though. The subquery that computes the counts still joins the roster to the contacts, and the planner still picks the order for that join. If it started from the contacts again, running the count once instead of twice would only cut the 126 seconds roughly in half. The repeated subquery doubled the cost, but the join order is what made each copy slow.
CROSS JOIN Pins the Join Order
In SQLite, writing CROSS JOIN instead of JOIN makes the planner keep the tables in the order you wrote them. The SQLite query planner docs describe this as the way to control the join order by hand: SQLite never reorders the tables in a CROSS JOIN. With an ON clause, it returns the same rows an inner join would. Only the order the tables are read in changes.
SELECT count(DISTINCT r.door_hash)
FROM van_turf_roster r
CROSS JOIN van_person_contacts c
ON c.campaign_id = ? AND c.person_hash = r.person_hash
WHERE r.turf_id = van_turf_checkouts.turf_id
AND c.last_in_person_at >= ?
AND c.last_in_person_at <= ?
That’s the whole change to the query. The roster is read first, by turf_id, and each person’s contact second, by primary key. The update went from 126 seconds to under a tenth of a second.

This is SQLite behavior. In standard SQL, CROSS JOIN is a Cartesian product and takes no ON clause, so check what your database does with it before borrowing the technique.
A one-word fix is also easy to undo by accident. Someone tidying the SQL later could see a CROSS JOIN with an ON clause and take it for a typo. So the fix has two safeguards. The first is a comment above the query saying why the word is there, including the 126 seconds. The second is a test that captures the statement the function sends, runs EXPLAIN QUERY PLAN on it, and checks that every search of the contacts table goes by person_hash:
const plan = await client.execute({ sql: `EXPLAIN QUERY PLAN ${stmt.sql}`, args: stmt.args });
const contactSearches = plan.rows
.map((row) => String(row.detail))
.filter((detail) => detail.startsWith('SEARCH c '));
expect(contactSearches.length).toBeGreaterThan(0);
for (const detail of contactSearches) expect(detail).toContain('person_hash=?');
If the planner ever goes back to starting from the contacts, this test fails.
The Same Mistake in Another Query
The 126-second update wasn’t the only query the planner got wrong. Turso’s Top Queries view, ranked by total time, had one statement far ahead of everything else. It averaged about 27 seconds, read around 35 million rows each time, and ran almost 30 times in a day. It came from the job that imports new contacts. After an import, it finds every list with one of the newly contacted people on its roster, 500 people at a time:
SELECT DISTINCT r.turf_id
FROM van_turf_roster r
JOIN van_turfs t ON t.turf_id = r.turf_id
WHERE t.campaign_id = ? AND r.person_hash IN (…500 hashes…)
The roster has an index on person_hash, and the plan didn’t use it:
SEARCH t USING COVERING INDEX van_turfs_campaign_folder (campaign_id=?)
SEARCH r USING COVERING INDEX sqlite_autoindex_van_turf_roster_1 (turf_id=? AND person_hash=?)
The planner started from every list in the campaign, old ones included, and checked each list’s roster for each of the 500 people. That’s millions of lookups for a batch that matches a few hundred rows. With a CROSS JOIN and the roster first, the plan becomes:
SEARCH r USING INDEX van_turf_roster_person (person_hash=?)
SEARCH t USING INTEGER PRIMARY KEY (rowid=?)
Each person is found through the index on person_hash, and their list by its primary key. A test checks that the plan starts from that index and never searches lists by campaign, and it fails against the old query.
The daily door report already had a CROSS JOIN for the same reason, and I’d added one as a precaution to the organizers’ page that shows how many doors each volunteer has knocked. That made four queries on the same tables where I’d overridden the planner’s order. Every time one of them ran slow, the planner had started from everything the campaign had in one table (all its contacts, or all its lists) and done a lookup for each row.
The Real Fix Was ANALYZE
Four queries on the same tables with the same override meant the problem wasn’t in the queries. Each CROSS JOIN fixed one query I had already found, and the next slow join would only show up when a page took half a minute to load. Something was making the planner wrong about all of them.
SQLite picks a join order using statistics: each table’s row count and how selective each index is. ANALYZE collects them and writes them to a table called sqlite_stat1. This database had never been analyzed. Without statistics, SQLite assumes every table has about a million rows, so a table of a few thousand rows and the roster’s 2.5 million looked the same size to it. Every join order seemed about equally good, and on these tables it kept picking the wrong one.
So the fix was to give the planner statistics, and a few things came up along the way:
- Turso refuses a sampled
ANALYZE. I planned to cap the work at about a thousand rows per index withPRAGMA analysis_limit, to keep the write lock short. Turso answeredSQL not allowed statement: PRAGMA analysis_limit = 1000. PlainANALYZEis allowed, and it reads every row of every index while holding the write lock. - The big tables take real time. Run one table at a time, the roster’s 2.5 million rows took about 16 seconds, the contacts table’s 640,000 (every campaign’s) took about 8, and the 80,000 lists took about a second.
- Partial statistics are worse than none. After the large tables, the small ones still had no statistics, so the planner assumed each held a million rows. That made a tiny table look bigger than the table of 80,000 lists. A full
ANALYZEthe same night filled them in. Analyze every table or none of them.
Statistics go stale as tables grow, so a scheduled job refreshes them nightly in the early morning, at a minute no other job starts on. It runs one ANALYZE per table, one request each, so a write queued behind it waits for one table at most (about 16 seconds for the roster). A table that fails is logged by name, and the rest still run. A migration that adds an index ends with ANALYZE on its table, so the planner has statistics for the new index right away instead of the next night. If the statistics ever make plans worse, this returns the planner to its defaults:
DELETE FROM sqlite_stat1;
ANALYZE sqlite_schema;
With statistics, the contact import’s query starts from the index on person_hash on its own.
Checking Every Plan in CI
Statistics fix the planner in production, but tests run against databases with a handful of rows. Every plan is fast on a tiny database, so the tests say nothing about what production will do.
So I added a plan audit to CI. It pulls production’s sqlite_stat1 into a JSON file, which holds table names, index names, and row counts, and no data. Then it runs the whole test suite with every database client wrapped, records each statement the app sends along with the function that sent it, and plans each one with EXPLAIN QUERY PLAN against a migrated database loaded with production’s statistics. Any plan that reads every row of a table with 10,000 or more rows fails the build, unless it’s on an allow list with a written reason.
The first run planned more than 500 statements from app code, and about a dozen of them read a whole large table. One of them, the query behind the /turfs page where volunteers browse lists on a map, was urgent.
That page normally shows only current lists, and the table has indexes that hold just those rows (the lists whose retired_at is null). The page also keeps showing each volunteer the list they signed up for, even after that list is retired and replaced by a newer one. That exception was added to the query’s WHERE with an OR:
… AND (retired_at IS NULL OR turf_id IN (…the viewer's lists…)) AND …
The indexes hold only current lists, and the OR lets retired lists match too, so SQLite couldn’t use them. For any volunteer who currently had a list, the plan was a scan of the whole table:
SCAN van_turfs
That’s all 80,000-plus rows, including each list’s map outline, every time they loaded the page. The logs had shown /turfs loads of up to 8 seconds but not the cause, and join order had nothing to do with it. I fixed it by finding the matching list IDs first, looking up each side of the condition on its own (current lists through a new index, the volunteer’s own lists by ID), and then reading those rows by primary key. After the fixes, the audit finds no statement that reads a whole large table except a handful allowed by design.
Why I Kept the CROSS JOINs
With statistics in place and the audit in CI, the CROSS JOINs could come out. I left all of them in.
Statistics have gaps. A new index has none until its migration or the nightly job analyzes it. When a big load of new lists drops the roster’s index on person_hash to write millions of rows faster, then rebuilds it, the rebuilt index has none until the next refresh. A refresh can fail. During any of those windows the planner is back to guessing, and on these tables I know what it guesses. Where the planner already picks the order I wrote, the CROSS JOIN changes nothing. Where it doesn’t, the CROSS JOIN is the difference between a tenth of a second and two minutes with every write waiting.
Each one has a comment saying which order it holds and why, so nobody mistakes it for a typo.
Give the Planner What It Needs
CROSS JOIN is a useful tool in SQLite. It’s one word, the results don’t change, and it replaces the planner’s guess with an order you chose. Use it on your big joins, comment each one, and back it with a test that checks the plan.
If you find yourself pinning join orders over and over, though, check whether the planner has statistics at all. Run ANALYZE on the whole database, refresh it on a schedule, and check your query plans in CI against production’s statistics instead of your test data’s. If you’ve never looked, run SELECT * FROM sqlite_stat1 on your production database. If it fails with “no such table” or comes back empty, your planner has been guessing.