Slow SQL? Don't Add Hardware Yet: Read the Query Plan, Then Add the Index
Author 137's books, 20000 rows: SCAN takes 0.177 s for 200 runs, one index makes it 0.012 s, 14.9x faster, same 100 rows. JOIN and subquery both return 2000 rows in about 0.020 s, and a covering index drops the temp B-tree sort. SQLite 3.45.1, stdlib only.

The most common slow query in AI-generated code is not wrong SQL, it is SQL that makes the database read the whole table: to find one author's books, the database first looks through all 20000 books row by row, then picks out the 100 you wanted. With a small table nothing feels wrong, but as the data grows, the page starts spinning, and the most useless response is to add an index by feel, or to do the opposite and add hardware or a cache, while the real slow spot is never touched. The right approach is to read the query plan first: EXPLAIN QUERY PLAN tells you how the database intends to run the query, whether it is a full table scan or an index lookup, which index it uses, and whether there is a temporary sort, and only then do you decide which index to add. This guide uses a fictional book catalog, 20000 books, 200 authors, 10 countries, and only the Python standard library sqlite3. The demo script is demo249_g2.py, run on Python 3.12.3 and SQLite 3.45.1, and the Chinese and English runs share the same logic and conclusions, only the timings come from each run, and each matches its own transcript.
The conclusion first: looking up author 137's books, with no index, 200 runs take 0.177 seconds, and the plan is a single line, SCAN books; after adding one index on the author, 200 runs take 0.012 seconds, the plan becomes SEARCH books USING INDEX idx_books_author (author_id=?), 14.9x faster, and the rows returned are 100 in both cases — the answer did not change at all. The JOIN versus subquery pair is interesting too: finding French authors' books, both forms return 2000 rows, the JOIN takes 0.019 seconds for 200 runs and the subquery 0.020 seconds, almost identical, because the query planner rewrote them into nearly the same path. The last pair shows a covering index also removing the temporary B-tree sort. In short: read the plan before optimizing, let the plan tell you what is missing, and then add exactly that, instead of guessing first.
Read the query plan before optimizing anything
Section 1 of the demo does only one thing: before adding any index, look at the query plan. For SELECT title FROM books WHERE author_id = 137, the plan is one line: SCAN books. That means the database reads the whole table from start to finish, checking each row for author 137, keeping the matches and throwing the rest away. The official query planner docs put it plainly: with a table of 7 rows, a full table scan is acceptable; with 7 million rows, a full table scan might read megabytes of content to find a single 8-byte number, so one normally tries to avoid full table scans. The demo table has 20000 rows, and scanning it 200 times takes 0.177 seconds. That number is not large by itself, but next to the 0.012 seconds that follow, it tells you where the problem is.
One concept needs to be clear first, or the plan will be confusing: SQL is a declarative language, not a procedural one. When you write SQL you tell the database what you want to compute, not how to compute it; figuring out the how is delegated to the query planner inside the database engine. For any given statement, hundreds or thousands of algorithms could produce the correct answer, some faster and some slower, and the planner's job is to pick the fastest and most efficient one. The docs say the planner usually does a good job, but it needs indexes to work with, and those indexes must normally be added by programmers. That sentence is the whole method of this guide: your job is not to design the algorithm for the database, it is to prepare the indexes for it, and then use the plan to check whether it actually used them.
There is also a note about EXPLAIN QUERY PLAN itself, from the official EXPLAIN docs: its output is intended for interactive analysis and troubleshooting only, the format may change between SQLite releases, and applications should not use it. In other words, the plan is for you to read, not for your program to parse and branch on. The demo uses it that way: the script prints the plan for a human to read, and the timings and row counts are what the program judges by itself. A few keywords are enough to read a plan: SCAN is a full table scan, SEARCH is an index lookup, USING INDEX is followed by the index that was used, USING COVERING INDEX is a covering index, and USE TEMP B-TREE FOR ORDER BY is a temporary sort. The next sections cover each of them in turn.
One more habit belongs here: the same SQL can produce a completely different plan at a different data size. The demo table has 20000 rows, and looking up author 137 through an index is fast; if the table had only 100 rows, the planner might decide a full scan is cheaper and hand you a SCAN, and that is not a bug — on a tiny table, scanning once costs less than going through an index, which adds an extra hop. So the idea that every SCAN must be eliminated is itself wrong. Whether a SCAN is a problem depends on how big the table is, how many rows one query scans, and how many times a day the query runs. Scanning a 20000-row table 200 times in 0.177 seconds is under 0.001 seconds per run; if the query runs a few times a day, it is not worth optimizing at all, but if it runs hundreds of times a second, that gap becomes real lag. The priority of an optimization is always the plan times the call count, never the plan alone.
Another point that is easy to miss: the plan shows the path for this query with this data distribution, and when the distribution changes, the path can change too. In the demo, 200 authors each wrote exactly 100 books, a very even distribution, and the planner picks the index decisively; in a real project the data is often skewed, for example one author wrote 15000 books while the other 199 wrote 5000 between them, and then looking up the prolific author narrows the gap between an index lookup and a full scan, because three quarters of the table has to be returned anyway, so the planner might pick SCAN directly. The official docs mention that after ANALYZE runs, the planner has statistics about the indexes and knows which one usually narrows the search the most; without ANALYZE, the choice of index is arbitrary. The demo is too small to need ANALYZE, but once a real project grows large and skewed, ANALYZE is what lets the planner choose correctly, and it is worth running once after importing data.
Add one index: full scan becomes index search
Section 2 of the demo does exactly one thing: CREATE INDEX idx_books_author ON books(author_id), an index on the author column. What is an index? The official docs give a clear picture: an index is another table much like the original, but with the column you search on placed in front and all rows in content order, followed by each row's rowid. To find author 137's books, the database binary-searches the index for the first entry with that author, takes the rowid, then binary-searches the original table for that rowid — two binary searches instead of scanning 20000 rows. The demo numbers confirm this: the plan changes from SCAN books to SEARCH books USING INDEX idx_books_author (author_id=?), 200 runs go from 0.177 seconds to 0.012 seconds, 14.9x faster.
One detail is worth noting: the index did not change the answer, only how fast it is found. Before the index, the query returned 100 rows; after the index, it still returns 100 rows, because author 137 wrote exactly 100 books, and that number comes from the data, not from the index. The docs stress this too: indexes should never change the answer, only help the database get to the answer more quickly. If the results change after adding an index, something else is wrong; check the data first, then the SQL, and do not blame the index. This property has a practical benefit: to verify an optimization has no side effects, compare the rows and their contents before and after adding the index, and if they match, the optimization is safe. That is exactly how Section 2 of the demo verifies it.
Indexes are not free, and the demo's scale does not show it, so it needs saying in advance. Every index you add is one more index to maintain when writing data, so inserts, updates, and deletes all get slower, and the index itself takes space. On a 20000-row table that cost is invisible, but on a table that takes hundreds of thousands of writes a day, too many indexes slow writes down noticeably. So the rule for adding indexes is: read the plan first, find the query that is actually slow, add an index only on the column the WHERE clause really filters on, and read the plan again to confirm the index is actually used. The demo index follows that rule: the query filters on author_id = 137, and the index is on author_id, one to one, no more and no less.
JOIN vs subquery: same answer, not always the same path
Section 3 of the demo compares two ways of writing the same thing: French authors' books. The JOIN version joins the books table to the authors table and filters by country; the subquery version first finds the French authors' ids in the authors table, then looks them up in the books table with IN. Both return 2000 rows, exactly as expected: there are 20 French authors, each wrote 100 books, and 20 times 100 is 2000. But the timings may surprise you: the JOIN takes 0.019 seconds for 200 runs, the subquery 0.020 seconds, almost no difference, and neither is clearly faster.
The plans explain why. The JOIN plan is SCAN authors | SEARCH books USING COVERING INDEX idx_books_author (author_id=?): scan the 200 authors to find the 20 French ones, then use the index to find each one's books. The subquery plan is SEARCH books USING COVERING INDEX idx_books_author (author_id=?) | LIST SUBQUERY 1 | SCAN authors: scan the authors table to compute the subquery list first, then use the index to find the books. The details differ, but the core work is the same: find the 20 French authors first, then use the same index to find their books, so the times come out nearly the same. The query planner did its job here: no matter which way you express I want French authors' books, it picks a similarly good path.
The lesson of this section is not that JOIN and subquery are equally fast, but that you cannot guess speed from how the query is written — only the plan tells you. With a different table or a different data distribution, the conclusion could be completely different: if there were 190 French authors instead of 20, the subquery list would be huge and the planner might choose another path; if neither table had an index, the gap between the two forms could open up. The demo numbers only mean something for the demo's data: 200 authors, 10 countries, 100 books each, and under that distribution the two forms tie. In a real project, do what the demo does: write both forms, run the plan for each, time each, and let the numbers decide, not your intuition.
The chart above shows both comparisons at a glance, and the numbers match the demo transcript exactly. On the left, two bars: without an index, 0.177 seconds is a tall bar, and with an index, 0.012 seconds is nearly flat on the ground, a 14.9x gap, and the value of the index is visible at once. On the right, two bars: the JOIN at 0.019 seconds and the subquery at 0.020 seconds are almost the same height, showing at a glance that the two forms make no difference on the demo's data. Together the two charts are the core conclusion of this guide: read the plan before optimizing, an index solves the how to find it problem, and whether one way of writing a query is better depends on the path the planner finally picks, not on whether you wrote a JOIN or a subquery.
Covering index: skip the table lookup and the sort
Section 4 of the demo is about covering indexes, which solve two problems at once, the table lookup and the sort. The lookup first: after an ordinary index finds a rowid, the database has to go back to the original table to fetch that row and get the columns you asked for, and that step is called a table lookup. If every column the query needs is already in the index, the database never goes back to the table at all; it reads the answer straight from the index, and that is a covering index. The demo query is SELECT author_id, year FROM books WHERE author_id = 137 ORDER BY year, asking only for the author id and the year, and the new index is idx_cover ON books(author_id, year), which contains both columns, so the plan shows USING COVERING INDEX idx_cover, and the table lookup is gone.
Then the sort: the same query carries an ORDER BY year, asking for results ordered by year. Before the covering index, the plan was SEARCH books USING INDEX idx_books_author (author_id=?) | USE TEMP B-TREE FOR ORDER BY, where the second part means the 100 rows found still had to be sorted once in a temporary B-tree, because the ordinary index is ordered by author id only, not by year. After the covering index, the plan becomes SEARCH books USING COVERING INDEX idx_cover (author_id=?), and the temporary B-tree line is gone, because the covering index is ordered by author id and then by year, so reading author 137's books already yields them in year order, and no extra sort is needed. One index removed both the lookup and the sort; that is the value of a multi-column index.
A multi-column index has a rule about order, and the docs state it clearly: the left-most column is the primary key used for ordering the rows in the index, and each following column breaks ties for the ones before it. The demo index is (author_id, year), author first and year second, so it serves both filtering by author and ordering by year after filtering by author. But it does not help a query that filters only by year, because year is not the left-most column and the rows in the index are not ordered by year. Before adding a multi-column index, think about which columns the WHERE clause and the ORDER BY clause each use, and order them as filter first, sort second, with the filtering column on the left and the sorting column on the right, so one index does two jobs instead of being built and never used.
When not to add an index
Everything so far has been about the benefits of indexes; this section turns it around: indexes are not free, and there are three situations to be careful about. The first is a write-heavy table: indexes are built for reads, and every write has to maintain each extra index, so inserts, updates, and deletes all get slower; a log table that is only written and never read gains nothing but trouble from an index. The second is a low-selectivity column: a column with only two values, yes and no, split evenly, gives an index lookup almost no advantage over a full scan, and the planner will most likely pick SCAN anyway, so the index is built for nothing. The third is a small table: scanning a few hundred rows is fast already, and the time an index saves is too small to measure, while it still takes space and maintenance, so it is better not to build one.
There is a simple way to decide whether an index is worth adding: read the plan first, then look at the numbers. When the plan shows a SCAN, ask three questions: how big is the table, how many times a day does this query run, and what share of the whole table do the returned rows make up? Big table, frequent runs, small share of rows returned — when all three are true, an index is worth adding; when only one is true, leave it alone and spend the time somewhere more valuable. The demo query meets all three: a 20000-row table, only 100 rows returned, 0.5% of the table, so the 14.9x improvement is real. The other way around, the French authors' query returns 2000 rows, 10% of the table, so the index's gain is less dramatic, which is part of why the JOIN and the subquery in Section 3 both hover around 0.019 to 0.020 seconds: the rows returned are themselves a large share, and the index only saves the finding time, not the returning time.
Closing checklist and boundaries
Here is everything above as a checklist: when a query feels slow, run EXPLAIN QUERY PLAN first, and check whether it says SCAN or SEARCH, which index it uses, and whether there is a temporary sort; once you find a full table scan, add an index only on the column the WHERE clause really filters on, then read the plan again and confirm the SEARCH line names the index you just built; try both the JOIN and the subquery forms, read both plans, time both, and do not guess speed from how the query is written; if every column the query needs is in the index, build a covering index, and the table lookup and the sort may both disappear; and before and after every optimization, compare the row counts, because an optimization is only safe when the answer does not change — in the demo, the 100 rows and the 2000 rows stayed the same before and after the indexes.
Finally, what this guide does not cover, so you do not take query plans into fights they are not meant for: it does not cover SQL basics. The site's SQL basics guide covered SELECT, JOIN, GROUP BY, and window functions, and the SQLite guide covered creating databases and tables; this guide covers only query optimization, and it assumes you can already write SQL. It does not go deep into ANALYZE; the official docs mention that ANALYZE helps the planner gather statistics about indexes and pick better ones, but the demo is too small to need it, and it becomes worth reading once the data grows. It does not cover optimizing writes; indexes optimize reads, and too many of them slow writes down, so balancing reads and writes is another topic. And it does not cover caching or adding hardware; those solve different problems, and if the query itself takes the wrong path, a cache only gives you the wrong answer faster. One last boundary note: this guide continues the site's SQL basics guide and SQLite guide. Those two covered how to store data and how to get data out; this one covers what to do when getting it out is too slow — how to read the plan, how to add an index, and how to prove the change really made it faster.
Comments (0)
Sources
Related articles
Building stock of 2000 books moves current memory from 0.3 KiB to 582.7 KiB; subtracting two snapshots, the biggest line is line 85 at 568.1 KiB and 9699 blocks; getsizeof sees only 15.8 KiB, and clearing brings the line back to 0.0 KiB. Python 3.12.3 stdlib, measured.
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.
GCC 13.3.0, C17, zero packages: a first C program, sizeof results 1/2/4/8/8/4/8/8, sum 1..100 is 5050, 10! is 3628800, 8 numbers sorted, 3 books total 1088 pages, 3 file lines and 70 chars read back. Preprocessing alone expands 3 lines to 815.