Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 140/ 160
07. Indexing, Query Optimization & Performance Tuning

End-to-End Query Tuning Case Studies (Turning a 30s Query into 30ms)

Walk real tuning loops: measure, explain, index/rewrite, and verify wins.

AdvancedMeasure · Rewrite / Index3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Case 2, rewrittenQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  c.id,3  c.name,4  lo.last_order5FROM6  customers c7  LEFT JOIN (8    SELECT9      customer_id,10      MAX(created_at) AS last_order11    FROM12      orders13    GROUP BY14      customer_id15  ) lo ON lo.customer_id = c.id16WHERE17  c.region = 'west';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/17
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative western customers3 sample rows
Representative western customers
idnamelast_order
101Asha Rao2026-11-19 14:20:00
108Kunal Shah2026-11-02 08:45:00
115Mira SenNULL

Note: Sample data includes two customers with orders and one without any; LEFT JOIN keeps the unmatched customer with a NULL last_order.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Case 3's fix in the load jobQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1COPY staging_events2FROM3  '/data/events.csv'4WITH5  (FORMAT csv, HEADER);67ANALYZE staging_events;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command responses2 sample rows
Representative command responses
statementstatus
COPYCOPY 3
ANALYZEANALYZE

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

The planner now knows the table has 5 million rows, not 0.

Key takeaway: Misestimates → ANALYZE; deep OFFSET → keyset pagination.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Measure

Pick the query that matters

Rank by total time (calls × mean) in pg_stat_statements or the slow log, not by single slowest run.

SQL at this step
1ORDER BY2  total_exec_time DESC
What to watch at this step
Impact
calls × time
Tip: use ← → to move between steps

When 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

Missing or mismatched index / non-sargable filter
Best for: Seq Scans with highly selective filters

Strengths: Often 100–1,000× faster with a rewrite plus composite index.

Watch out: Extra index maintenance on writes.

Bad estimates (stale statistics)
Best for: Plans with estimated vs actual rows off by orders of magnitude

Strengths: ANALYZE is cheap and needs no code change.

Watch out: Must be built into load jobs, or it recurs.

Query shape (per-row subqueries, deep OFFSET)
Best for: Loops=thousands, or time growing with page number

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?
Interview tip: Tell tuning stories with numbers before and after: time, rows and pages. A short story with real figures is more convincing than a list of techniques.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Identifying Slow Queries (pg_stat_statements & Slow Query Logs)
Next topic
Transactions (BEGIN, COMMIT, ROLLBACK, SAVEPOINT)