Skip to content
We areTOP 1%

How would you find and fix a slow SQL query?

HardConceptIndexing & Query Optimization
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

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, JOIN and ORDER BY. A composite index on (a, b) serves filters on a or on a and b, but not on b alone, 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 TABLE in 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

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account