After learning about SQL indexes and how they can speed up queries, the next step is determining when and how to use them effectively. This tutorial introduces a four-step benchmarking process for comparing the efficiency of different query/index setups. Think of it like a “before and after” test: you measure a query’s performance, apply an index, then measure again to see if you’ve improved matters.
First, figure out how your database is currently fulfilling your query. Is it scanning every row, or using an index to limit lookups?
EXPLAIN QUERY PLAN [your_query] in SQLite3 to see the query strategy.
For example, if you have a cookies table and want to see
how the DB finds cookies of type “sugar,” you might do:
sqlite> EXPLAIN QUERY PLAN SELECT * FROM cookies WHERE type = 'sugar';
If it says SCAN cookies, you know you’re not using an index.
If it says something like SEARCH cookies USING INDEX idx_cookies_type,
an index is being applied.
Next, record how long your query takes without any new index changes:
sqlite3 myDatabase.db.timer onSELECT * FROM cookies WHERE type = 'sugar';Run Time: real 0.003 user 0.000000 sys 0.000000This time is your baseline. Keep it noted somewhere so you can compare after making changes.
Now, create an index that you believe will help. For instance:
sqlite> CREATE INDEX idx_cookies_type ON cookies(type);
Then run EXPLAIN QUERY PLAN again:
sqlite> EXPLAIN QUERY PLAN SELECT * FROM cookies WHERE type = 'sugar';
If it now says SEARCH cookies USING INDEX idx_cookies_type (type=?),
you’ve confirmed the index is being utilized for the query.
If it still says SCAN, you might need a different column order or a multi-column index.
Finally, time the same query again with the index in place:
sqlite> .timer on
sqlite> SELECT * FROM cookies WHERE type = 'sugar';
-- ... check run time ...
Compare this new time to your baseline. Has the run time decreased, stayed the same, or increased?
DROP INDEX idx_cookies_type and try a different approach.
Here’s a simplified process:
.timer on.This systematic approach is how you fine-tune SQL performance. Without measurement and iteration, you could guess incorrectly or build unnecessary indexes that don’t actually help your real queries.
.timer on in sqlite3 to see how long it takes without a new index.
EXPLAIN QUERY PLAN again
to ensure it’s used.
By following these steps, you can avoid guesswork and systematically improve the efficiency of your SQL queries in any large data scenario.