Tech Interview RoomStudy guides

SQL Fundamentals

How do you find and fix a slow query? Explain EXPLAIN plans.

Intermediate · 2 min read · Lesson 7 of 8 in SQL Fundamentals

A repeatable process

  1. Find the slow queries: slow query log (MySQL), pg_stat_statements (PostgreSQL), AWR/ASH reports (Oracle), Query Insights (Cloud SQL), or APM traces.
  2. Read the plan with EXPLAIN (estimated) and EXPLAIN ANALYZE (actual rows and time; it runs the query).
  3. Look for: full scans on large tables, a big gap between estimated and actual rows (stale statistics), nested loops over many rows, sorts or hashes spilling to disk, and filters applied after reading many rows.
  4. Fix, then measure again.

Common fixes

  • Add or adjust an index (composite in the right order, covering, partial).
  • Make predicates sargable: no functions on indexed columns, matching data types.
  • Select only needed columns; avoid SELECT * in hot paths.
  • Paginate with keyset pagination (WHERE id > :last ORDER BY id LIMIT 50) instead of large OFFSETs, which read and discard rows.
  • Fix N+1 queries from the ORM (fetch joins, batch fetching).
  • Update statistics (ANALYZE); rewrite correlated subqueries as joins; pre-aggregate.
  • Partition very large tables by date so queries touch only relevant partitions.

Example

sql
EXPLAIN ANALYZE
SELECT o.id, o.amount
FROM orders o
WHERE o.customer_id = 42 AND o.status = 'PAID'
ORDER BY o.created_at DESC
LIMIT 20;

-- Before: Seq Scan on orders (rows=5,000,000) + Sort  → 850 ms
-- Fix:
CREATE INDEX idx_orders_cust_status_created ON orders (customer_id, status, created_at DESC);
-- After: Index Scan using idx_orders_cust_status_created (rows=20) → 0.3 ms

-- Keyset pagination instead of OFFSET 100000
SELECT id, amount, created_at FROM orders
WHERE customer_id = 42 AND (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 20;

Follow-up questions interviewers ask

Try answering each one before you open it.

Why is EXPLAIN ANALYZE dangerous on an UPDATE?

It actually executes the statement. Wrap it in a transaction and roll back (BEGIN; EXPLAIN ANALYZE UPDATE ...; ROLLBACK;), or use plain EXPLAIN for the estimated plan.