Your First Slow Query: A Beginner's Look at EXPLAIN
One day a query in your project will feel slow. Before guessing, you can ask the database how it plans to run the query. That is what EXPLAIN does. This post is a gentle first look; it will not make you a tuning expert, but it will make the next steps less mysterious.
What a query plan is
When you send SQL, you describe *what* you want, not *how* to get it. The database decides the how: which table to read first, whether to use an index, how to combine rows. That decision is the query plan. EXPLAIN shows it to you.
Trying it in SQLite
Make a table with plenty of rows, then ask for the plan:
EXPLAIN QUERY PLAN
SELECT * FROM songs WHERE artist = 'Nina';
Without an index on artist, you will see something like:
SCAN songs
SCAN means SQLite reads every row and checks each one. Now add an index and ask again:
CREATE INDEX idx_songs_artist ON songs (artist);
EXPLAIN QUERY PLAN
SELECT * FROM songs WHERE artist = 'Nina';
SEARCH songs USING INDEX idx_songs_artist (artist=?)
SEARCH ... USING INDEX means it jumps straight to the matching rows, like using the index at the back of a book.
Trying it in PostgreSQL
EXPLAIN SELECT * FROM songs WHERE artist = 'Nina';
The words differ: Seq Scan on songs means reading the whole table, and Index Scan using idx_songs_artist means using the index. PostgreSQL also shows estimated costs and row counts in brackets. As a beginner you can ignore the numbers at first and just look at the words.
A small vocabulary
| You see | It means |
|---|---|
| SCAN (SQLite), Seq Scan (PostgreSQL) | Reading every row |
| SEARCH, Index Scan | Using an index to find rows |
| USE TEMP B-TREE FOR ORDER BY (SQLite), Sort | Sorting rows because no index gives the order |
Is a scan always bad?
No. On a small table, reading everything is fast, and databases sometimes choose a scan on purpose because it is cheaper than jumping around an index. A scan becomes a concern when the table is large, the query runs often and only a few rows are needed.
A beginner's checklist for a slow query
- Run EXPLAIN and look for a scan on a big table.
- Check whether the column in your WHERE clause has an index.
- Check that your WHERE clause uses the column directly, not inside a function.
- If your page runs the same small query once per item in a list, the problem may be the number of queries rather than any one query.
Where to go next
This is enough to start. When you want to read full plans with timings, design indexes for several columns or fix slow pages in a real application, our sister site databaseintegrate.com covers those topics for working developers. Here on the .org, indexes for beginners is the natural next read.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.
Get new pages by email