Interview Q&A · SQL · 8 questions in this topic

Scenario-Based Questions — SQL Interview Q&A

All SQL topics

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

  1. 1Diagnose — EXPLAIN ANALYZE, estimates vs actuals.
  2. 2Access — indexes, stats, sargability.
  3. 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

  1. 1Freeze — same filters, zones, NULL rules.
  2. 2Diff — EXCEPT both ways to isolate.
  3. 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

Example.sqlsql
CREATE UNIQUE INDEX ux_users_email ON users (LOWER(email));

💡 Constraints-are-truth is the principle to state.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits