Last Minute Notes

Database Interview Playbook

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.

📘 Database Interview Playbook

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.

Table of Contents

  1. What Interviewers Look For
  2. Question Bank
  3. Schema Design Prompts
  4. Production Scenarios
  5. Cheat Sheets
  6. Common Mistakes
  7. Study Plans

1. What Interviewers Look For

LevelExpected
JuniorCorrect SQL for joins and aggregates, keys and normalization, what an index is, basic ACID
MidWindow functions, query tuning with EXPLAIN, composite indexes, isolation levels and their anomalies, schema design with constraints, N+1 and pagination
SeniorMVCC 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
StaffData 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.


2. Question Bank

Sixty questions, with a checklist of what a strong answer includes.

2.1 Fundamentals (15)

#QuestionStrong answer includesRead
1Primary key vs unique key vs foreign key?Uniqueness, nullability, one per table, referential integrityFundamentals
2Surrogate vs natural key?Stability, size, keep a unique constraint on the natural key, UUIDv7 vs bigintFundamentals
3What is normalization? Explain 1NF, 2NF, 3NF.Anomalies, atomic values, whole key, nothing but the keyFundamentals
4When do you denormalize?Measured read problem, snapshots, read models, single source of truthFundamentals
5Why is NULL = NULL not true?Three-valued logic, IS NULL, NOT IN trap, aggregates ignore NULLFundamentals
6DELETE vs TRUNCATE vs DROP?Rows vs all rows vs the object, logging, triggers, rollbackFundamentals
7How do you model many-to-many?Junction table, composite key, attributes on the relationshipData Modeling
8Why never store money as float?Binary rounding, integer cents or NUMERIC plus currencyFundamentals
9OLTP vs OLAP?Workload, row vs column store, normalized vs star schemaFundamentals
10What does a foreign key ON DELETE CASCADE do?Child deletion, risks, RESTRICT alternativeFundamentals
11What are ACID properties?Each letter with a mechanism, C is app invariants not CAP's CTransactions
12SQL vs NoSQL: how do you choose?Access patterns, consistency, scale, team, start relationalNoSQL
13What is a view and a materialized view?Saved query vs stored result, refresh, usesSQL Essentials
14What is a stored procedure or trigger and when to avoid them?Server-side logic, hidden behavior, testing and versioningSQL Essentials
15Explain CAP in the database context.Partition forces C or A, examples, PACELCFundamentals

2.2 SQL (10)

#QuestionStrong answer includesRead
16WHERE vs HAVING?Before vs after grouping, aggregatesSQL Essentials
17INNER vs LEFT vs FULL join, and the LEFT JOIN plus WHERE trapUnmatched rows, filter in ON to keep themSQL Essentials
18RANK vs DENSE_RANK vs ROW_NUMBERTies and gaps, top N per groupSQL Essentials
19Find the Nth highest salaryDENSE_RANK, distinct, NULL result, tiesPractice
20Delete duplicate rows keeping oneROW_NUMBER partition, verify with SELECT firstPractice
21Longest consecutive login streakGaps and islands, dedupe, date minus row numberPractice
22Customers who never orderedAnti join, NOT EXISTS vs NOT INPractice
23Month-over-month growthAggregate then LAG, divide by zeroPractice
24What is a recursive CTE and when do you use it?Anchor plus recursive term, hierarchies, cycle guardSQL Essentials
25Why does SUM double count after a join?One-to-many fan-out, pre-aggregateSQL Essentials

2.3 Indexing and Performance (10)

#QuestionStrong answer includesRead
26How does a B-tree index work?Sorted pages, shallow tree, log n, range scans, write costIndexing
27Leftmost prefix rule and column order?Equality, sort, rangeIndexing
28Why is my index not used?Non-sargable predicate, selectivity, types, statsIndexing
29Covering index and index-only scan?All columns in the index, INCLUDE, visibility mapIndexing
30Clustered vs non-clustered (InnoDB vs Postgres heap)Row placement, secondary index lookups, PK widthIndexing
31How do you debug a slow query?Reproduce, EXPLAIN ANALYZE, estimates vs actual, fix, re-measureIndexing
32Offset vs keyset paginationDeep offset cost, stable cursor, index on sort keyIndexing
33What is the N+1 problem?Symptom, joins, eager loading, batchingIndexing
34Costs of too many indexes?Write amplification, space, planner, HOT updatesIndexing
35Add an index to a huge live table safelyCONCURRENTLY, online DDL, monitoring, rollbackOperations

2.4 Transactions and Concurrency (10)

#QuestionStrong answer includesRead
36List isolation levels and anomaliesDirty, non-repeatable, phantom, lost update, write skewTransactions
37What does PostgreSQL Repeatable Read actually do?Snapshot isolation, no phantoms, write skew possibleTransactions
38Explain MVCCRow versions, snapshots, readers do not block writers, vacuumTransactions
39Prevent overselling inventoryAtomic conditional UPDATE, CHECK, affected rowsTransactions
40Prevent double bookingUnique constraint, exclusion constraint, FOR UPDATE, holdsTransactions
41What is a deadlock and how do you handle it?Wait-for cycle, victim, lock ordering, retryTransactions
42Optimistic vs pessimistic lockingVersion column, FOR UPDATE, contention trade-offTransactions
43Explain write skew and a fixOn-call example, serializable, lock rows read, materialize conflictTransactions
44SELECT FOR UPDATE SKIP LOCKED use caseJob queue, no blocking, batch claimsTransactions
45How does the WAL give durability and speed?Log before data, sequential, fsync, group commit, replayInternals

2.5 Internals, Scale and NoSQL (15)

#QuestionStrong answer includesRead
46B-tree vs LSM treeWrite path, amplification, compaction, workloadsInternals
47Nested loop vs hash vs merge joinCosts, when each wins, memory, sorted inputInternals
48Why do wrong row estimates hurt?Join order and method choice, multiplying error, ANALYZEInternals
49Why are column stores fast for analytics?Column pruning, compression, vectorization, zone mapsInternals
50Scale a read-heavy PostgresQuery fixes, cache, replicas with lag routing, pool, partition, shardOperations
51Sync vs async replication, and lag mitigationData loss vs latency, read-your-writes techniquesOperations
52How does failover work and fail?Detect, elect, fence, promote, split brainOperations
53Partitioning vs shardingOne database vs many, pruning, retention, shard keyOperations
54Change a column type with zero downtimeExpand, dual write, backfill, switch, contract, lock timeoutOperations
55Restore to before an accidental DELETEBase backup plus WAL replay (PITR), into a new instanceOperations
56Embed vs reference in MongoDBRead together, bounded, atomicity, patternsNoSQL
57DynamoDB hot partition and single-table designKey cardinality, write sharding, access patterns firstNoSQL
58Cassandra consistency levels and modelingRF, QUORUM overlap, query-first tables, tombstonesNoSQL
59Model a hierarchy or SCD Type 2Adjacency, path, closure, valid_from and valid_toData Modeling
60Multi-tenant schema optionsShared with tenant_id and RLS, schema, database, isolation vs costData Modeling

3. Schema Design Prompts

For each, follow the process: entities, relationships, access patterns, keys, constraints, indexes, growth. Say the grain, and list the queries before drawing tables.

PromptKey tablesPoints to hit
E-commercecustomers, products, orders, order_items, inventory, paymentsPrice snapshot on lines, money in cents, inventory CHECK, order status machine, idempotent payments, index on (customer_id, created_at)
Twitter-likeusers, posts, follows, likes, feed cacheFollows as (follower_id, followee_id) with both-direction indexes, counters denormalized, fan-out choice, keyset pagination
Chatusers, conversations, participants, messagesMessages keyed by (conversation_id, id), read receipts as a per-participant pointer, partition by time or conversation
Ticket or seat bookingevents, shows, seats, holds, bookingsUNIQUE (show_id, seat_id) on confirmed bookings, hold expiry, no double booking, see movie booking
Bank or walletaccounts, ledger_tx, ledger_entriesDouble entry, immutable, derived balances, idempotency keys, no floats
Splitwiseusers, groups, expenses, expense_shares, settlementsInteger cents, shares sum to total, netting, see Splitwise code
Library or hotel bookingbooks/copies or rooms, members, loans or reservationsDate range overlap constraint (exclusion), availability query, copy vs title
Ride hailingriders, drivers, trips, locationsTrip state machine, driver locations in a fast store not the OLTP table, geo index
URL shortenerurlsKey lookup, code primary key, expiry, click events in an append-only store
Analytics for an appfact_events, dim_user, dim_dateStar schema, grain, partition by date, columnar storage

4. Production Scenarios

Answer these the way you would in an on-call incident: mitigate first, then find the cause.

ScenarioFirst movesRoot causes and fixes
A query got 100x slower after a deployCompare plans before and after, check recent index and stats changesMissing 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 timeOne hot query, missing index, N+1 from a new endpoint, cache miss storm. Index, batch, cache
"Too many connections"Count connections by state and applicationPool too large or leaking, serverless connection storm, long idle-in-transaction. Pooler, timeouts, right-size pools
Deadlocks in productionRead the deadlock graph in the logInconsistent lock order, wide transactions, missing index causing many locked rows. Order locks, shorten transactions, retry
Replica lag spikesLag graph, replica CPU and I/O, long queries on the replicaLarge batch write on the primary, conflicting long queries, under-provisioned replica. Throttle batches, split work, route fresh reads to primary
Primary disk almost fullFind the biggest tables, WAL and temp usage, replication slotsBloat 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 siteFind the blocked ALTER and its blockerLock queue behind a long transaction. Set lock_timeout, use concurrent or online DDL, run off-peak
Customers were charged twiceLook for retries without idempotencyMissing unique idempotency key, client retry after timeout. Add the constraint, reconcile
Stock went negative or was oversoldLook for read-then-write in the appNo atomic conditional update or check constraint. Atomic UPDATE ... WHERE qty >= n, CHECK
Reports slow the app downIdentify the heavy queries and their locksAnalytics on the primary. Read replica with limits, warehouse, materialized views
Data missing after failoverCompare last LSN of old and new primaryAsynchronous replication loss window. Use synchronous or quorum commit for critical data, reconcile
Table has 5x the expected sizeCompare live vs dead tuples, index sizesBloat from long transactions or aggressive updates. Vacuum tuning, pg_repack, fillfactor

5. Cheat Sheets

5.1 SQL

Logical order:   FROM/JOIN  WHERE  GROUP BY  HAVING  SELECT  DISTINCT  ORDER BY  LIMIT
NULL:            IS NULL, COALESCE, NOT EXISTS (not NOT IN), aggregates skip NULL, COUNT(*) counts rows
Top N per group: ROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC) in a subquery, filter rn <= N
Streaks:         value - ROW_NUMBER() is constant within a run, GROUP BY that
Running 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.end
Upsert:          INSERT ... ON CONFLICT DO UPDATE  (MySQL: ON DUPLICATE KEY UPDATE)
Safe update:     SELECT with the same WHERE first, run inside BEGIN, check row count

5.2 Indexes and Plans

Composite order:   equality columns, then sort column, then range column
Sargable:          column = constant, range on the raw column. Not: function(column), leading %, type mismatch
Read the plan:     SCAN vs SEARCH, estimated vs actual rows, rows removed by filter, sort, loops, buffers
Index costs:       every write updates every index, space, planner choices, HOT updates
Paging:            keyset (WHERE (created_at, id) < (?, ?)) not OFFSET

5.3 Transactions

AnomalyRead CommittedRepeatable Read / SnapshotSerializable
Dirty readNoNoNo
Non-repeatable readYesNoNo
PhantomYesMostly no (PostgreSQL no)No
Lost updatePossibleDetected in PostgreSQL, prevented by lock in MySQLNo
Write skewYesYesNo
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 n
Deadlock:      same lock order, short transactions, retry on 40P01 or 1213
Serializable:  always retry on 40001

5.4 Scale and Operations

Scale path:      fix queries, cache, scale up, pool, read replicas, partition, shard, distributed SQL
Replication:     async fast but lossy, sync or quorum safe but slower, lag breaks read-your-writes
Failover:        detect, elect, FENCE, promote, repoint, rebuild old primary
Migrations:      expand, dual write, backfill in batches, switch, contract, always lock_timeout
Backups:         base backup plus WAL archive = PITR, test restores, 3-2-1, immutable copy
Shard key:       high cardinality, even load, matches the main query, not time

5.5 Which Database

NeedPick
Default for a productPostgreSQL
Cache, counters, leaderboards, queuesRedis or Valkey
Serverless key access at any scale on AWSDynamoDB
Evolving documentsMongoDB or Postgres JSONB
Huge write rate, multi-datacenterCassandra or ScyllaDB
Text searchElasticsearch or OpenSearch (derived from the primary)
Semantic searchpgvector, then a vector database at scale
AnalyticsClickHouse, BigQuery, Snowflake, DuckDB
Global SQL with transactionsSpanner, CockroachDB, Aurora DSQL
Embedded or edgeSQLite

6. Common Mistakes

MistakeBetter
Writing SQL without asking about NULLs, ties and duplicatesAsk, then state the assumption
Answering a tuning question with "add an index"Reproduce, read the plan, then justify the index and its write cost
Reciting isolation levels without engine specificsSay what PostgreSQL and MySQL actually do
Ignoring failure and lag in replication answersCover data loss, lag, failover and fencing
Proposing sharding firstWalk the scaling ladder and say when sharding is justified
Choosing NoSQL by fashionStart from access patterns and consistency needs
No mention of constraintsPut invariants in the database
Forgetting migrations and operationsMention online DDL, backups and monitoring
Vague words ("fast", "scalable")Numbers: rows, QPS, latency, growth

7. Study Plans

7.1 Four Weeks

WeekLearnPractice
1: Foundations and SQLFundamentals, SQL EssentialsWrite every example from memory, then solve problems 1 to 12 in Practice
2: Performance and modelingIndexing, Data ModelingRead plans on a real dataset, problems 13 to 20, design three schemas from section 3
3: Concurrency and internalsTransactions, InternalsReproduce a lost update, a deadlock and write skew with two terminals, explain B-tree vs LSM aloud
4: Scale, NoSQL, mocksReplication and Operations, NoSQLTwo 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.

7.2 Seven-Day Crash Plan

DayFocus
1Keys, constraints, normalization, NULL semantics, joins
2Aggregation, subqueries, CTEs, window functions
3The SQL practice problems (patterns: top N, streaks, retention, intervals)
4Indexes, composite order, EXPLAIN, sargability, pagination
5Transactions, isolation, MVCC, locks, deadlocks, oversell and double booking patterns
6Replication, failover, sharding, migrations, backups, choosing a database
7Mock 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.

On this page