End-to-End Query Tuning Case Studies (Turning a 30s Query into 30ms)
Walk real tuning loops: measure, explain, index/rewrite, and verify wins.
In plain words
Find the slowest query, see where it wastes time, fix one thing, and check it really got faster.
Think of it like…
A doctor's process: check the symptoms (measure), run a test (EXPLAIN), make a diagnosis (hypothesis), prescribe one treatment, and check again before trying anything else.
Where you’ve seen it
Case 1: a dashboard query, SELECT … FROM orders WHERE DATE(created_at) = current_date AND store_id = $1, takes 30 s on 120 M rows. The plan shows a Seq Scan reading 1.4 M pages. Rewriting the filter as created_at >= current_date AND created_at < current_date + 1 and adding an index on (store_id, created_at) gives an Index Scan reading 60 pages, and the query takes 30 ms.
Words you’ll hear
- Tuning loop
- Measure → reproduce → hypothesise → change one thing → verify.
- Baseline
- Time, rows and buffers recorded before any change.
- Correlated subquery
- A subquery re-run for each outer row; often rewritten as a join or LATERAL.
- Regression check
- Confirming other queries and writes didn't get slower.
Visual diagram
Theory & example queries
Cases 1 and 2: the filter and the per-row subquery
Case 1 (above) is the classic pair: a function on the column (DATE(created_at)) hides the index, and the existing single-column index on created_at isn't the best shape anyway. The fix is a sargable range plus a composite index in equality-then-range order. Verification: buffers fall from 1.4 million to about 60, and the plan shows an Index Scan with both conditions in Index Cond.
Case 2: an admin page lists 5,000 customers with (SELECT MAX(created_at) FROM orders o WHERE o.customer_id = c.id) AS last_order. The plan shows a SubPlan with loops=5000, each scanning orders because there's no index on customer_id: 22 seconds. Adding an index on orders (customer_id, created_at) turns each loop into a one-entry index read, 25 ms; alternatively, aggregating orders once with GROUP BY and joining gives 180 ms without the new index.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT c.id, c.name, lo.last_orderFROM customers c LEFT JOIN ( SELECT customer_id, MAX(created_at) AS last_order FROM orders GROUP BY customer_id ) lo ON lo.customer_id = c.idWHERE c.region = 'west';PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative western customers3 sample rows
| id | name | last_order |
|---|---|---|
| 101 | Asha Rao | 2026-11-19 14:20:00 |
| 108 | Kunal Shah | 2026-11-02 08:45:00 |
| 115 | Mira Sen | NULL |
Note: Sample data includes two customers with orders and one without any; LEFT JOIN keeps the unmatched customer with a NULL last_order.
Key takeaway: Sargable range + composite index; per-row subqueries need an index or a set-based rewrite.
Cases 3 and 4: statistics and pagination
Case 3: after a nightly job loads 5 million rows into staging_events, a join that normally takes 2 s takes 11 minutes. The plan estimates 1 row from staging_events (actual 5 million) and picks a nested loop. The table's statistics are from before the load. Running ANALYZE staging_events as the last step of the load restores a hash join and the 2-second runtime. Lesson: when estimated and actual rows differ hugely, fix the statistics before the query.
Case 4: an export pages through orders with ORDER BY id LIMIT 1000 OFFSET n. Page 1 takes 3 ms, page 5,000 takes 4 s, because OFFSET reads and discards every earlier row. Switching to keyset pagination, WHERE id > $last_seen_id ORDER BY id LIMIT 1000, makes every page take about 3 ms. In each case, record before-and-after time, rows and buffers, and check that new indexes don't slow writes.
COPY staging_eventsFROM '/data/events.csv'WITH (FORMAT csv, HEADER);ANALYZE staging_events;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative command responses2 sample rows
| statement | status |
|---|---|
| COPY | COPY 3 |
| ANALYZE | ANALYZE |
Note: The sample file has three rows, so COPY 3 is intentionally illustrative; the real response reports the CSV's loaded row count. Statistics detail and refresh behavior vary by PostgreSQL configuration.
The planner now knows the table has 5 million rows, not 0.
Key takeaway: Misestimates → ANALYZE; deep OFFSET → keyset pagination.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Pick the query that matters
Rank by total time (calls × mean) in pg_stat_statements or the slow log, not by single slowest run.
ORDER BY total_exec_time DESCWhen to use it & trade-offs
What it is
Real query tuning follows a loop: measure which queries cost the most, reproduce one with EXPLAIN (ANALYZE, BUFFERS) on realistic data, form a hypothesis from the plan, change one thing, and verify with the same measurements before and after. This lesson walks through four common cases: a non-sargable date filter plus a missing composite index, a correlated subquery run once per row, stale statistics after a bulk load, and deep OFFSET pagination.
Why it matters: Knowing individual techniques isn't the same as knowing which to apply. Interviewers increasingly ask "tell me about a slow query you fixed" or give a plan and ask what you'd do first. Walking through cases with numbers shows a repeatable method rather than guesswork, and the same four causes account for a large share of real-world slow queries.
When to reach for it
- Interview answers about a slow query you fixed
- Triage of performance incidents
- Reviewing new queries before they ship
When to avoid or be careful
- Changing several things at once
- Testing fixes on tiny development data
- Declaring victory from a single warm-cache timing
Common causes and their fixes
Strengths: Often 100–1,000× faster with a rewrite plus composite index.
Watch out: Extra index maintenance on writes.
Strengths: ANALYZE is cheap and needs no code change.
Watch out: Must be built into load jobs, or it recurs.
Strengths: Set-based rewrites and keyset pagination scale flatly.
Watch out: Requires application changes.
Interview signals & numbers to know
When this topic comes up
- “Tell me about a slow query you optimised”
- “This dashboard takes 30 seconds”
- “It got slow after the nightly load”
- “Later pages of the export are slower”
- Performance methodology
Benchmarks & rules of thumb
- 30 s → 30 ms
- case 1 after rewrite and index
- loops=5000
- the sign of a per-row subquery
- 1 → 5 M
- case 3's estimate vs actual rows
Common mistakes & follow-ups
Common interview mistakes
- Adding three indexes and a rewrite together, then not knowing which one helped or which slowed inserts.
- Tuning a query that runs once a day while a 5 ms query run 4 million times a day uses far more database time.
- Fixing a bad plan with a hint or rewrite when the real cause was stale statistics.
Likely interviewer follow-ups
- Walk me through how you'd approach a query that suddenly got slow.
- How do you know your fix didn't make something else worse?
- What would you check first in a plan where estimated rows are 1 and actual rows are 5 million?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply End-to-End Query Tuning Case Studies (Turning a 30s Query into 30ms) with hands-on SQL practice and interview Q&A.