How would you find and fix a slow SQL query?
HardConceptIndexing & Query Optimization
Answer
Start by measuring: run EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL and MySQL 8, which also executes the query) to see the plan, and look for full table scans, large row estimates and expensive sorts. Then fix the cause.
- Add the right index on columns used in
WHERE,JOINandORDER BY. A composite index on(a, b)serves filters onaor onaandb, but not onbalone, so put equality columns first. - Keep conditions sargable (able to use an index): do not wrap the indexed column in a function, avoid leading wildcards such as
LIKE '%son', and avoid comparing a text column with a number. - Fetch less data: select only the needed columns instead of
SELECT *, filter early and paginate. - Refresh statistics with
ANALYZE(ANALYZE TABLEin MySQL) so the optimizer estimates correctly.
Example:
-- Slow: the function hides the indexed column
SELECT * FROM orders WHERE YEAR(order_date) = 2024;
-- Fast: a range on the bare column can use an index on order_date
SELECT * FROM orders
WHERE order_date >= '2024-01-01' AND order_date < '2025-01-01';
More in Indexing & Query Optimization
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is indexing in DBMS, and why does it make queries faster? | Concept | Easy | Read the answer to What is indexing in DBMS, and why does it make queries faster? | |||
| 2 | What is the difference between a B tree and a B+ tree? | Concept | Medium | Read the answer to What is the difference between a B tree and a B+ tree? | |||
| 3 | What is the difference between a clustered and a non-clustered index? | Concept | Medium | Read the answer to What is the difference between a clustered and a non-clustered index? | |||
| 4 | What is the difference between a dense index and a sparse index? | Concept | Medium | Read the answer to What is the difference between a dense index and a sparse index? | |||
| 5 | How would you find and fix a slow SQL query? | Concept | Hard | Read the answer to How would you find and fix a slow SQL query? |