Database interview preparation: a 60-question bank from beginner to advanced with pointers, schema design prompts, production incident scenarios with a triage flowchart, cheat sheets, common mistakes, and 4-week and 7-day study plans.
The other pages teach the material.
This page is for rehearsal: a bank of questions with what a strong answer contains, schema design prompts, incident scenarios, one-page cheat sheets, and study plans.
Correct SQL for joins and aggregates, keys and normalization, what an index is, basic ACID
Mid
Window functions, query tuning with EXPLAIN, composite indexes, isolation levels and their anomalies, schema design with constraints, N+1 and pagination
Senior
MVCC and locking behavior, deadlock and lost update prevention, replication lag and failover, partitioning and sharding trade-offs, zero-downtime migrations, choosing between engines with reasons
Staff
Data architecture across systems (OLTP, cache, search, warehouse), consistency and failure modes, capacity and cost, migration strategy, operational excellence
Signals that raise your rating: you state assumptions (dialect, data size), you consider NULLs and ties before writing SQL, you check the plan and the write cost of an index, and you name the failure mode of every choice.
For each, follow the process: entities, relationships, access patterns, keys, constraints, indexes, growth.
Say the grain, and list the queries before drawing tables.
Answer these the way you would in an on-call incident: mitigate first, then find the cause.
Scenario
First moves
Root causes and fixes
A query got 100x slower after a deploy
Compare plans before and after, check recent index and stats changes
Missing index for a new filter, plan flip after ANALYZE, ORM generated a different query, parameter skew. Fix the index or statistics, add a plan capture
Database CPU pegged at 100%
pg_stat_statements sorted by total time
One hot query, missing index, N+1 from a new endpoint, cache miss storm. Index, batch, cache
"Too many connections"
Count connections by state and application
Pool too large or leaking, serverless connection storm, long idle-in-transaction. Pooler, timeouts, right-size pools
Deadlocks in production
Read the deadlock graph in the log
Inconsistent lock order, wide transactions, missing index causing many locked rows. Order locks, shorten transactions, retry
Replica lag spikes
Lag graph, replica CPU and I/O, long queries on the replica
Large batch write on the primary, conflicting long queries, under-provisioned replica. Throttle batches, split work, route fresh reads to primary
Primary disk almost full
Find the biggest tables, WAL and temp usage, replication slots
Bloat from blocked vacuum, an abandoned replication slot holding WAL, unbounded log table. Drop the slot, vacuum, partition and archive, add disk
A migration blocked the site
Find the blocked ALTER and its blocker
Lock queue behind a long transaction. Set lock_timeout, use concurrent or online DDL, run off-peak
Customers were charged twice
Look for retries without idempotency
Missing unique idempotency key, client retry after timeout. Add the constraint, reconcile
Stock went negative or was oversold
Look for read-then-write in the app
No atomic conditional update or check constraint. Atomic UPDATE ... WHERE qty >= n, CHECK
Reports slow the app down
Identify the heavy queries and their locks
Analytics on the primary. Read replica with limits, warehouse, materialized views
Data missing after failover
Compare last LSN of old and new primary
Asynchronous replication loss window. Use synchronous or quorum commit for critical data, reconcile
Table has 5x the expected size
Compare live vs dead tuples, index sizes
Bloat from long transactions or aggressive updates. Vacuum tuning, pg_repack, fillfactor
Logical order: FROM/JOIN WHERE GROUP BY HAVING SELECT DISTINCT ORDER BY LIMITNULL: IS NULL, COALESCE, NOT EXISTS (not NOT IN), aggregates skip NULL, COUNT(*) counts rowsTop N per group: ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) in a subquery, filter rn <= NStreaks: value - ROW_NUMBER() is constant within a run, GROUP BY thatRunning total: SUM(x) OVER (ORDER BY t ROWS UNBOUNDED PRECEDING)Median: ROW_NUMBER and COUNT window, or PERCENTILE_CONT(0.5)Overlap: a.start < b.end AND b.start < a.endUpsert: INSERT ... ON CONFLICT DO UPDATE (MySQL: ON DUPLICATE KEY UPDATE)Safe update: SELECT with the same WHERE first, run inside BEGIN, check row count
Composite order: equality columns, then sort column, then range columnSargable: column = constant, range on the raw column. Not: function(column), leading %, type mismatchRead the plan: SCAN vs SEARCH, estimated vs actual rows, rows removed by filter, sort, loops, buffersIndex costs: every write updates every index, space, planner choices, HOT updatesPaging: keyset (WHERE (created_at, id) < (?, ?)) not OFFSET
Detected in PostgreSQL, prevented by lock in MySQL
No
Write skew
Yes
Yes
No
Oversell: UPDATE stock SET qty = qty - :n WHERE sku = :s AND qty >= :n (check rows affected)Optimistic: UPDATE ... SET v = v + 1 WHERE id = :id AND v = :seen (0 rows means retry)Queue: SELECT ... FOR UPDATE SKIP LOCKED LIMIT nDeadlock: same lock order, short transactions, retry on 40P01 or 1213Serializable: always retry on 40001
Scale path: fix queries, cache, scale up, pool, read replicas, partition, shard, distributed SQLReplication: async fast but lossy, sync or quorum safe but slower, lag breaks read-your-writesFailover: detect, elect, FENCE, promote, repoint, rebuild old primaryMigrations: expand, dual write, backfill in batches, switch, contract, always lock_timeoutBackups: base backup plus WAL archive = PITR, test restores, 3-2-1, immutable copyShard key: high cardinality, even load, matches the main query, not time
Two mock interviews per week, walk the production scenarios, review the question bank
Set up a local PostgreSQL (Docker: docker run -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres) and try the PostgreSQL-specific statements from these pages: EXPLAIN (ANALYZE, BUFFERS), FOR UPDATE SKIP LOCKED, CREATE INDEX CONCURRENTLY, isolation levels in two psql sessions.
Transactions, isolation, MVCC, locks, deadlocks, oversell and double booking patterns
6
Replication, failover, sharding, migrations, backups, choosing a database
7
Mock interview, production scenarios, the cheat sheets, sleep
Cross-links: for architecture-level questions ("design a URL shortener", "design a ticketing system") continue in System Design, and for how applications use databases see Backend.