Query Optimization
Read the database's plan for a query to find out why it's slow and how to speed it up.
What is it?
Guessing why a query is slow rarely works. You need to see what the database is doing. Most databases explain their plan before (or while) running a query, usually with an EXPLAIN command. It shows whether they scan every row, whether they use an index, and the estimated cost of each step.
Query optimization means reading that plan, spotting the expensive parts (often a full table scan where an index would help, or a badly ordered join), and fixing them. Usually that's adding an index, rewriting the query, or sometimes restructuring the schema.
Explain like I'm 10
EXPLAIN is like asking a delivery driver for their route before they leave. If they say 'I'll drive past every house in the city checking addresses,' you know why it's slow, and you can hand them a map (an index).
Examples
Reading a query plan
EXPLAIN SELECT * FROM orders WHERE customer_email = 'amara@example.com';
-- Output might show:
-- Seq Scan on orders (cost=0.00..18334.00 rows=1 width=72)
-- Filter: (customer_email = 'amara@example.com'::text)'Seq Scan' means a sequential (full table) scan: the database checks every row. On a large table, that's the part to fix.
After adding an index
CREATE INDEX idx_orders_customer_email ON orders (customer_email);
EXPLAIN SELECT * FROM orders WHERE customer_email = 'amara@example.com';
-- Output might now show:
-- Index Scan using idx_orders_customer_email on orders
-- (cost=0.42..8.44 rows=1 width=72)With the index, the plan switches to an 'Index Scan' at a far lower estimated cost. The database jumps to matching rows instead of checking every one.
How it works
Before running a query, the query planner considers several ways to run it (scan the whole table, use this or that index, join in one order or another). It estimates each one's cost and picks the cheapest, using statistics it keeps about the data (like row counts, or how many distinct values a column has).
EXPLAIN shows the chosen plan. EXPLAIN ANALYZE also runs the query and shows the real measured cost. Common fixes:
- add a missing index - rewrite the query to avoid something that blocks index use (like wrapping an indexed column in a function) - restructure an inefficient join
Why does it exist?
The planner is sophisticated but works from statistics and heuristics. It can choose badly, or a query can be written so it can't use an index it otherwise would. Seeing the actual plan turns "this query is slow" from guesswork into an evidence-based problem you can solve.
When to use it
Optimize when a query is measurably slow, or before shipping a new query against a table you expect to grow. Checking the plan early can catch a missing index before it hits production.
When not to use it
Don't optimize a query that's already fast and touches little data; premature optimization adds complexity for nothing. Focus on queries measured to be slow or that run very often.
Common mistakes
Adding an index without checking that the planner uses it. Sometimes the fix is rewriting the query, not adding an index.
Optimizing on a guess instead of reading the EXPLAIN output, and fixing the wrong thing.
Testing only on a small local database, where a full table scan is fast enough to hide a problem that appears at production scale.
Practice exercises
- Easy:
Explain what a 'Seq Scan' in a query plan tells you about how the database runs that query.
- Medium:
A slow query filters on an unindexed column. Describe the steps you'd take to diagnose and fix it.
- Hard:
Explain why wrapping an indexed column in a function in a WHERE clause (e.g. LOWER(email) = ...) can stop the database using that column's index.
Interview questions
What does the `EXPLAIN` command show you?
The plan the database will use for a query: whether it scans the whole table or uses an index, the order it joins tables, and the estimated cost of each step.
What's the difference between `EXPLAIN` and `EXPLAIN ANALYZE`?
EXPLAIN shows the plan and estimated costs without running the query. EXPLAIN ANALYZE runs it and adds the real row counts and timings.
Name one common fix for a slow query doing a full table scan.
Add an index on the column used in the WHERE clause or join condition, so the database can look up matching rows directly.
What's the difference between a `Seq Scan` and an `Index Scan` in a query plan?
A Seq Scan reads every row in order and checks each one. An Index Scan uses an index to jump straight to matching rows and skips the rest.
Why might the planner choose a `Seq Scan` even when an index exists on the filtered column?
If the table is small, or the filter matches a large share of rows, scanning directly can be cheaper than many random-access index lookups. An index only pays off when it narrows the result a lot.
What do the two numbers in a cost estimate like `cost=0.42..8.44` mean?
The first is the estimated startup cost (work before the first row can be returned). The second is the estimated total cost to return every row of that step.
What does the `rows=` estimate in an EXPLAIN plan represent, and where does it come from?
The planner's guess at how many rows the step returns, based on table statistics like row count and distinct values per column. It isn't an actual count.
Why can EXPLAIN ANALYZE show a very different 'actual rows' than the plan's estimated 'rows', and why does that matter?
The statistics are stale or the data is unusually distributed, so the cost estimates (and the chosen plan) may rest on a badly wrong guess. A big gap is a strong signal to re-run ANALYZE on the table.
What is an `Index Only Scan`, and how does it differ from a regular `Index Scan`?
A regular index scan finds entries in the index, then fetches the row from the table (the 'heap') for any column not in the index. An index-only scan answers from the index alone and skips that fetch.
What's a 'covering index', and why does it enable an index-only scan?
An index containing every column the query needs, not just the filtered one. Since nothing outside the index must be read, the database can skip the table's rows entirely.
Why does an index scan in Postgres often still need to fetch the row from the table, whereas MySQL's InnoDB frequently doesn't for primary-key lookups?
Postgres stores table data as an unordered heap with indexes pointing into it, so most index scans need a separate heap fetch. InnoDB clusters row data around the primary key, so a primary-key lookup already has the row.
What is a `Bitmap Heap Scan`/`Bitmap Index Scan` pair, and when does the planner use it instead of a plain index scan?
The bitmap index scan builds an in-memory map of which pages hold matching rows; the bitmap heap scan then visits just those pages in physical order. The planner prefers it when enough rows match that a plain index scan would cause too much random I/O.
Why does wrapping an indexed column in a function (e.g. `LOWER(email) = ...`) typically prevent the planner from using an index on that column?
A standard index stores raw column values, not function results. The planner can't match LOWER(email) against an index on plain email, so it checks every row.
Instead of wrapping the column in `LOWER()`, how would you index a case-insensitive lookup so the planner can still use it?
Create an expression (functional) index on the exact expression the query uses, e.g. CREATE INDEX ON users (LOWER(email)), so the index stores the lowercased values being filtered.
Why does a leading wildcard in `LIKE '%something'` prevent a standard B-tree index from helping?
A B-tree is ordered from the start of the value, so it can jump to a known prefix. A pattern that can match anywhere gives it no starting point, so every entry must be checked.
In a composite index on `(a, b)`, why can a query filtering only on `b` fail to use that index efficiently?
The index is ordered by a first, and by b only within each a. Without a condition on a, there's no way to find where matching b values are, so the whole index must be scanned.
Why does column order matter when creating a composite index meant to speed up a query filtering on multiple columns?
An index can only be searched efficiently from its leading column(s). Putting the most selective, most-filtered column first narrows the search fastest; the wrong order can make the index little better than a full scan.
What role does the `ANALYZE` command play in query planning (as distinct from `EXPLAIN ANALYZE`)?
ANALYZE recomputes the table statistics (row counts, distinct-value estimates, data distribution) the planner uses to estimate costs. Without it, statistics go stale and plans get worse.
What happens to query plans if a table's statistics are stale, for example right after a large bulk load, and how do you fix it?
The planner keeps costing plans from old row counts and distributions, and may pick a plan wrong for the table's new size or shape. Run ANALYZE (many databases also do this automatically on a schedule) to refresh the statistics.
At a high level, what's the difference between a nested loop join, a hash join, and a merge join?
Nested loop: for each row of one input, look up matches in the other (cheap when one side is small or well-indexed). Hash join: build an in-memory hash table from one side and probe it with the other (good for larger unsorted inputs). Merge join: walk both inputs together in sorted order (good when both are already sorted on the join key).
Why does join order matter for a multi-table query, and who decides it?
Different orders can hugely change how many intermediate rows are produced. The planner picks the order from estimated costs, unless there are so many tables that it falls back to heuristics instead of costing every ordering.
Given a tiny 4-row `orders` table with no `WHERE` clause at all, what would `EXPLAIN SELECT * FROM orders;` show, even with an index on `id`?
A Seq Scan on orders. With no filter, every row is returned anyway, so reading the table directly is at least as cheap as using an index, without the overhead. The index doesn't change that.
Debugging: a query has run fine in production for months and suddenly gets slow, with no change to the query text or schema. What's the first thing to check?
Whether the table's size or data distribution changed enough that the old plan (e.g. an index scan) is no longer cheapest, or the statistics went stale. Re-run EXPLAIN ANALYZE to see if the plan changed, and check when statistics were last updated.
Debugging: EXPLAIN shows the query is already using an index, but it's still slow. What's a likely reason?
The index matches many rows (low selectivity), so it barely narrows the work. Or the query needs columns outside the index and pays for a heap fetch on every matched row.
Why might adding an index make a table's writes slower, and how is that a tradeoff against faster reads?
Every insert, update, or delete must also update each index, so more indexes mean more work per write. Indexes trade some write throughput for faster reads on the columns they cover.
What's the practical effect of having too many indexes on a heavily written-to table?
Writes slow down because each one updates every index, and many of those indexes may barely be used. Review a table's indexes periodically against the real queries.
What's the difference between the 'cost' units shown by EXPLAIN and actual wall-clock time?
Cost is an abstract unit for comparing plans (roughly based on disk-page fetches and per-row work), not milliseconds. Only EXPLAIN ANALYZE's actual timings show real elapsed time.
What is a correlated subquery, and why can it be much slower than an equivalent join?
A subquery that uses a column from the outer query, so it reruns once per outer row. A join lets the planner process both tables together in one pass instead.
What does `EXPLAIN (ANALYZE, BUFFERS)` add over plain `EXPLAIN ANALYZE`, and why is that useful?
It shows how many data pages each step read from cache versus disk. That helps tell a step slowed by real disk I/O from one slow for another reason.
Why can two queries that return the same result set produce different EXPLAIN plans and different performance?
The planner works from the query's structure, not its intent. A rewrite (a join instead of a subquery, a different clause order, an extra redundant condition) can open up or rule out plan choices, even with identical results.
Why can a query that performs well in local testing turn out to be slow in production despite identical query text?
A small local dataset makes a full table scan fast enough to hide a missing index. The planner may also pick different plans at different sizes; a plan fine for thousands of rows can be wrong for millions.