Interview Q&A · SQL · 8 questions in this topic
Scenario-Based Questions — SQL Interview Q&A
Judgment questions — slow dashboards, duplicates, and design calls from real on-call rotations. Part of Scenarios & Rapid Fire · 192 questions in the SQL bank.
A dashboard query takes 30 seconds. How do you fix it?
Answer
EXPLAIN ANALYZE first — find the misestimated node, missing index, or fan-out. Then: sargable predicates, covering/composite indexes, pre-aggregation (rollup tables, materialized views), and result caching. Fix access paths before rewriting logic.
Measure-first methodology beats guess-indexing every time.
Key points
- 1Diagnose — EXPLAIN ANALYZE, estimates vs actuals.
- 2Access — indexes, stats, sargability.
- 3Precompute — rollups, materialized views, caching.
💡 Estimates-first is the methodology sentence.
Revenue numbers differ between two reports. How do you reconcile?
Answer
Freeze definitions (which table, which filters, NULL handling, time zone, dedup rule), reproduce both queries side by side, diff row sets (EXCEPT both directions), and trace to the divergent predicate — usually fan-out double-counting, timezone day boundaries, or NULL inclusion.
Metric definitions belong in versioned code (dbt/metrics layer), not tribal knowledge.
Key points
- 1Freeze — same filters, zones, NULL rules.
- 2Diff — EXCEPT both ways to isolate.
- 3Codify — definitions in versioned code.
Duplicate users keep appearing despite app checks. How do you stop them?
Answer
Race-proof with a UNIQUE constraint (partial/expression as needed) — application pre-checks race by construction. Backfill dedup (ROW_NUMBER keep-one), add the constraint, convert inserts to upserts.
The database is the only race-proof validator — app checks are UX, constraints are truth.
Example
CREATE UNIQUE INDEX ux_users_email ON users (LOWER(email));
💡 Constraints-are-truth is the principle to state.
The primary database is overloaded with reads. What are your options?
Answer
Read replicas for replica-safe queries (with lag tolerance), caching (query/result caches with invalidation), pre-aggregation (rollups, materialized views), and query shaping (narrow columns, pagination). Writes stay on the primary; replica lag bounds what reads can move.
Lag-tolerance decides placement: dashboards yes, balances no.
Key points
- 1Replicas — lag-tolerant reads off primary.
- 2Precompute — rollups and caches.
- 3Shape — narrow, paginated, indexed.
How do you migrate a live table (add column, backfill, rename)?
Answer
Expand-contract: add nullable (or NOT VALID constraint), backfill in batches, validate, then constrain/enforce; renames via view/alias compatibility shim, clients moved before old name drops. Each step deploys independently with rollback.
Zero-downtime is staged compatibility, not big-bang rewrites.
Key points
- 1Expand — nullable additions first.
- 2Backfill — batched, resumable.
- 3Contract — enforce after clients move.
How do you delete old data (retention) without downtime?
Answer
Partition by time (drop whole partitions — instant, no bloat), or batched deletes with pauses (small transactions, replication-friendly), or TTL shims. Single giant DELETE locks, bloats and lags replicas.
Partition-drop is the gold standard; batched-delete the fallback.
Example
-- batched fallback (repeat, advancing): DELETE FROM events WHERE created_at < '2023-01-01' LIMIT 10000;
💡 Partition-drop-first is the senior answer.
How do you review a SQL pull request? What do you check first?
Answer
Correctness first (WHERE correlation, NULL handling, fan-out before aggregates, destructive-WHERE preview), then performance (EXPLAIN on new shapes, index coverage, N+1 risk), then safety (parameters not interpolation, least-privilege fit).
A review that debates formatting while missing an uncorrelated DELETE has failed.
Key points
- 1Correctness — predicates, NULLs, fan-out.
- 2Performance — EXPLAIN, indexes, N+1.
- 3Safety — parameters, privileges.
💡 Semantics before style is the reviewer credo.
How do you test SQL (migrations, queries, data quality)?
Answer
Ephemeral test databases (template/transaction-wrapped) with fixture seeds, migration up/down runs in CI, query result assertions on known datasets, and data-quality checks (uniqueness, null-rate, freshness monitors) in production.
Seeded-dataset assertions turn queries into tested code.
Key points
- 1Migrations — up/down in CI on copies.
- 2Queries — asserted results on fixtures.
- 3Data — quality monitors in prod.
Recommended resourcesAffiliate links · may earn us a commission