SQL interview questionsQuestion 12 of 14
SQL interview question · Question 12 of 14
How would you optimize a slow analytical SQL query?
Short answer
I start with the query plan to see where the time goes: large scans, expensive joins, sorts or aggregations. Then I reduce the data read by selecting only needed columns and filtering on partition, cluster or indexed columns without wrapping them in functions. Next I fix joins (correct keys, no accidental fan-out, broadcasting small tables) and remove repeated work, and finally I confirm the faster query returns exactly the same result.
Detailed explanation
Structure the answer as a process; interviewers listen for measurement first.
- Reproduce and measure. Note runtime and data scanned. Check whether it is slow every time or only under load (queueing, concurrency).
- Read the plan. Find the operator that dominates: a full scan, a large shuffle or sort, a nested-loop join, an exploding join.
- Read less. Project only needed columns; filter on partition or clustering columns so the engine prunes files or micro-partitions.
- Make filters sargable. Compare raw columns to ranges instead of applying functions (
created_at >= ... AND created_at < ...instead ofCAST(created_at AS DATE) = ...). - Fix joins. Matching key types, unique keys where expected, aggregate before joining, broadcast small dimensions in distributed engines.
- Remove repeated work. Correlated subqueries, CTEs evaluated twice, unnecessary
DISTINCTorORDER BY. - Verify. Same row count and key aggregates as before.
Example
-- Before: scans every partition, transforms the column
SELECT * FROM events WHERE CAST(event_ts AS DATE) = DATE '2026-10-01';
-- After: only needed columns, prunable range filter
SELECT user_id, event_type
FROM events
WHERE event_ts >= TIMESTAMP '2026-10-01 00:00:00'
AND event_ts < TIMESTAMP '2026-10-02 00:00:00';
If the plan looks fine
Look outside the query: data volume growth, skewed keys, stale statistics, small-file problems, warehouse size or concurrency limits, and whether the result could be pre-aggregated or incrementally maintained.
Common mistakes
- Jumping to “add an index” without evidence.
- Not checking that the optimised query gives the same answer.
- Ignoring the cost side: a bigger warehouse is a fix, but not a free one.
Progress is saved in this browser only. No account needed.