Interviewers who ask situational database questions rarely care whether you can write a JOIN. They want to see whether you can reason about what the database actually does under load: which index a query uses, what a transaction can and cannot see, who is waiting on which lock, and what happens to a 40-million-row table when someone runs a migration at 3 p.m. This guide covers the concepts behind strong answers. The examples use PostgreSQL syntax because it is the most common reference point, and differences with MySQL (InnoDB) are called out where they change the answer. For each concept, learn the mechanism, then the trap. Senior answers usually start with the trade-off and the measurement you would take before changing anything.
Study order
If time is short, go in this order.
- Indexes, selectivity and reading query plans
Most production performance questions reduce to whether a query uses the right index, and reading a plan is the skill interviewers probe first.
- Isolation levels and the anomalies they allow
Lost updates and write skew show up in nearly every concurrency scenario; you need to name the anomaly and the fix.
- Row locks, lock waits and deadlocks
Explains outages caused by long transactions and deadlocks, and the SKIP LOCKED queue pattern is a frequent follow-up.
- Constraints, idempotency and integrity in the database
Unique constraints and idempotency keys are the correct answer to many duplicate-write and retry questions.
- Schema changes without downtime
Senior candidates are expected to know which schema changes lock tables and how to roll them out safely.
- Connection limits and pooling
Connection exhaustion is a common real incident, and pooler trade-offs separate experienced engineers from the rest.
- Replication lag, read replicas and failover
Read scaling and failover questions hinge on understanding lag and read-your-writes consistency.
- Keyset pagination instead of large OFFSETs
A compact, frequently asked topic that tests whether you understand how OFFSET actually executes.
Indexes, selectivity and reading query plans
A B-tree index lets the database find rows in O(log n) instead of scanning the whole table, but only if the query's predicates match the index's leading columns. A composite index on (customer_id, created_at) serves WHERE customer_id = ? and WHERE customer_id = ? ORDER BY created_at, but not WHERE created_at > ? alone. Column order should follow equality filters first, then range filters or sort columns.
The planner chooses between sequential scan, index scan, index-only scan and bitmap scans based on estimated row counts from table statistics. If a filter matches 30 percent of a table, a sequential scan is often cheaper than thousands of random index lookups, so an unused index is not automatically a bug. Use EXPLAIN (ANALYZE, BUFFERS) and compare estimated rows with actual rows: a large mismatch points to stale or insufficient statistics.
Every index costs write throughput, disk and memory. In an interview, mention that you would check the query plan, the frequency of the query and the write volume of the table before adding one.
SQL
-- Larder, a grocery delivery app: 40M rows in orders.
-- Hot query: a customer's 20 most recent orders.
CREATE INDEX CONCURRENTLY idx_orders_customer_created
ON orders (customer_id, created_at DESC);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents, created_at
FROM orders
WHERE customer_id = 81234
ORDER BY created_at DESC
LIMIT 20;
-- Expect: Index Scan using idx_orders_customer_created, no Sort node.The index matches the equality filter and the sort, so the database reads 20 entries and stops.
Traps
- Wrapping an indexed column in a function, as in
WHERE lower(email) = ?, prevents use of a plain index on email. Use an expression index or store normalised data. - Putting a range column before an equality column in a composite index forces the database to scan a wider slice of the index.
- Implicit type casts, such as comparing a text column to a number, can silently disable index use.
- Adding an index for every slow query bloats writes; check for existing indexes that already cover the leading columns.
- Reading only
EXPLAINwithoutANALYZEshows estimates, not reality, and hides misestimates.
Isolation levels and the anomalies they allow
Isolation levels define which concurrency anomalies a transaction can observe. Read Committed, the PostgreSQL default, gives each statement a fresh snapshot, so two reads in the same transaction can return different values. Repeatable Read, the InnoDB default, keeps one snapshot for the whole transaction. Serializable guarantees the result is equivalent to some serial order of transactions.
The anomaly interviewers like most is the lost update: two requests read a balance of 100, each subtracts 30 in application code, and both write 70. Read Committed does not prevent it. Fixes are an atomic UPDATE ... SET x = x - 30, a row lock with SELECT ... FOR UPDATE, or optimistic concurrency with a version column. Write skew is subtler: two transactions read the same set of rows, each updates a different row, and together they break an invariant. Only Serializable, or explicit locking of the rows the decision depends on, prevents it.
Stricter levels are not free. In PostgreSQL, Repeatable Read and Serializable abort conflicting transactions with SQLSTATE 40001, and the application must retry the whole transaction.
SQL
-- Tallyho wallet: debit 30 credits without a lost update.
-- Wrong: SELECT balance, compute in code, then UPDATE ... SET balance = 70.
-- Right: let the database do the arithmetic and enforce the invariant.
UPDATE wallets
SET balance = balance - 30
WHERE id = 552 AND balance >= 30
RETURNING balance;
-- Zero rows returned means insufficient funds; no race possible.A single conditional UPDATE is atomic, so concurrent debits cannot both succeed past the balance check.
Traps
- Assuming the default level is the same everywhere: PostgreSQL uses Read Committed, MySQL InnoDB uses Repeatable Read, and their Repeatable Read implementations behave differently.
- Switching to Serializable without adding retry logic for serialization failures.
- Retrying only the failed statement instead of the entire transaction after a 40001 error.
- Believing transactions alone prevent race conditions; read-then-write logic in application code still races at Read Committed.
Row locks, lock waits and deadlocks
Writes take row-level locks that are held until the transaction commits or rolls back. Readers in MVCC databases like PostgreSQL and InnoDB do not block writers for plain SELECTs, but two writers on the same row queue up. Long transactions therefore turn into long lock waits, and a request that holds a lock while calling an external API can stall every other request touching that row.
A deadlock happens when transaction A holds lock 1 and waits for lock 2 while B holds lock 2 and waits for lock 1. The database detects the cycle and aborts one transaction. The usual cause is inconsistent ordering, such as transferring between two accounts and locking them in request order. Locking rows in a deterministic order, for example ascending id, removes that cycle.
SELECT ... FOR UPDATE SKIP LOCKED is the standard way to build a work queue in SQL: each worker claims rows nobody else holds instead of waiting. Set lock_timeout on risky operations so they fail fast instead of piling up.
SQL
-- Printfleet: 12 workers pull label-printing jobs from one table.
BEGIN;
SELECT id, payload
FROM print_jobs
WHERE status = 'pending'
ORDER BY id
LIMIT 10
FOR UPDATE SKIP LOCKED;
-- worker processes the batch, then:
UPDATE print_jobs SET status = 'done' WHERE id = ANY(ARRAY[101, 102, 103]);
COMMIT;Each worker grabs up to 10 unlocked jobs; rows claimed by other workers are skipped rather than waited on.
Traps
- Keeping a transaction open across network calls or user think time, which holds locks far longer than the SQL needs.
- Locking rows in the order they arrive in the request, which makes deadlocks between opposite transfers inevitable under load.
- Treating deadlock errors as fatal instead of retrying the transaction.
- Forgetting that
UPDATEon a parent row can block or be blocked by foreign key checks from inserts into child tables.
Keyset pagination instead of large OFFSETs
LIMIT 50 OFFSET 100000 forces the database to produce and discard 100,000 rows before returning 50, so page cost grows linearly with page depth. It is also unstable: if rows are inserted or deleted between requests, users see duplicates or miss items.
Keyset (cursor) pagination remembers the last row of the previous page and asks for rows after it. With an index on the sort columns, each page costs roughly the same regardless of depth. The sort must be on a unique key, so ties on a timestamp are broken with the primary key, and PostgreSQL's row-value comparison (created_at, id) < (?, ?) expresses this concisely and can use a composite index.
The trade-off is that you cannot jump to page 400 directly. For feeds, exports and APIs that is rarely needed; for admin tables that need numbered pages, a capped OFFSET or a search index is often acceptable.
SQL
-- Quillbox: a support inbox listing 2M tickets newest-first.
CREATE INDEX idx_tickets_created_id ON tickets (created_at DESC, id DESC);
-- First page
SELECT id, subject, created_at FROM tickets
ORDER BY created_at DESC, id DESC
LIMIT 50;
-- Next page: pass the last row's values as the cursor
SELECT id, subject, created_at FROM tickets
WHERE (created_at, id) < ('2024-05-02 09:14:00+00', 873221)
ORDER BY created_at DESC, id DESC
LIMIT 50;The cursor is the last (created_at, id) pair; the index makes every page an index range scan.
Traps
- Paginating on a non-unique column alone, which skips or repeats rows that share the same timestamp.
- Sorting in a different direction from the cursor comparison, which returns the wrong slice.
- Exposing raw cursor values that leak internal ids; encode them opaquely if that matters.
- Using row-value comparison in a database that cannot use an index for it; check the plan or expand it into OR conditions.
Schema changes without downtime
Schema changes take locks, and on busy tables the lock queue matters more than the change itself. In PostgreSQL, ALTER TABLE needs an ACCESS EXCLUSIVE lock; if it waits behind a long-running query, every new query on that table queues behind the ALTER, and the application stalls. Always set a short lock_timeout and retry.
Some operations are cheap: adding a nullable column, or since PostgreSQL 11 adding a column with a constant default, only changes metadata. Others rewrite or scan the table: changing a column type, adding NOT NULL directly, or creating an index without CONCURRENTLY. The safe alternatives are CREATE INDEX CONCURRENTLY, and adding a CHECK constraint as NOT VALID then validating it separately, which needs a weaker lock.
For renames and type changes, use expand and contract: add the new column, dual-write from the application, backfill in small batches, switch reads, then drop the old column in a later deploy. Old and new application versions run side by side during a rollout, so each migration must be compatible with both.
SQL
-- Ferrystack: make shipments.carrier_code mandatory on a 60M-row table.
SET lock_timeout = '3s';
ALTER TABLE shipments
ADD CONSTRAINT shipments_carrier_code_not_null
CHECK (carrier_code IS NOT NULL) NOT VALID;
-- Backfill in batches of 5,000 from a job, then:
ALTER TABLE shipments
VALIDATE CONSTRAINT shipments_carrier_code_not_null;
-- PostgreSQL 12+ uses the validated check to skip the full scan here:
ALTER TABLE shipments ALTER COLUMN carrier_code SET NOT NULL;NOT VALID adds the constraint instantly for new rows; validation scans existing rows without blocking writes.
Traps
- Running a migration with no lock_timeout, so it silently queues behind an analytics query and blocks all traffic.
- Renaming or dropping a column in the same deploy that stops using it, breaking instances still running the old code.
- Backfilling millions of rows in one UPDATE, creating a huge transaction, replication lag and table bloat.
- Assuming
CREATE INDEX CONCURRENTLYcan run inside a transaction block; it cannot, and a failed run leaves an INVALID index to drop.
Connection limits and pooling
Connections are expensive. PostgreSQL forks a backend process per connection, and throughput usually drops well before max_connections is reached because of contention and memory use. If 40 application pods each open a pool of 20, that is 800 potential connections, which can exhaust the server during a deploy when old and new pods overlap.
Keep per-instance pools small and size them from the database's capacity, not the application's request rate: a useful starting point is a small multiple of the database's CPU cores across all clients combined, then measured. An external pooler such as PgBouncer in transaction mode multiplexes many client connections onto few server connections.
Transaction pooling has a cost: a client gets a different server connection per transaction, so session state does not survive. Session-level SET, advisory locks held across transactions, LISTEN, and temporary tables break or behave unpredictably. Also watch for idle in transaction sessions, which hold locks and connections while doing nothing.
SQL
-- Diagnose connection pressure on the Larder primary.
SELECT state, count(*) AS sessions,
max(now() - state_change) AS longest_in_state
FROM pg_stat_activity
WHERE datname = 'larder'
GROUP BY state
ORDER BY sessions DESC;
-- Kill sessions stuck idle in a transaction for over 5 minutes.
ALTER DATABASE larder SET idle_in_transaction_session_timeout = '5min';Many idle-in-transaction sessions usually mean application code that opens a transaction and forgets to close it.
Traps
- Raising max_connections to fix pool exhaustion, which often makes latency worse.
- Forgetting that every replica, cron job and migration tool also consumes connections.
- Using session features like advisory locks or SET through a transaction-mode pooler.
- Setting pool acquire timeouts longer than the HTTP timeout, so requests pile up waiting for connections they will never use.
Replication lag, read replicas and failover
Most production setups stream changes from a primary to one or more replicas. Asynchronous replication is the default: the primary commits without waiting for replicas, so replicas lag by milliseconds normally and by minutes during a heavy backfill or a long query on the replica. Routing reads to replicas scales read load but breaks read-your-writes: a user saves a profile and the next page, served from a replica, shows the old value.
Common mitigations are routing a user's reads to the primary for a short window after they write, pinning a session to the primary for critical flows, or comparing a replication position (such as an LSN) before reading. Synchronous replication removes data loss on failover for committed transactions but adds a network round trip to every commit and can stall writes if the synchronous replica is down.
Failover with asynchronous replication can lose the last transactions the primary committed but did not ship. Know your recovery point objective and say it out loud in an interview.
SQL
-- Run on a replica: approximate lag of replayed changes.
SELECT now() - pg_last_xact_replay_timestamp() AS replay_lag;
-- Run on the primary: per-replica lag in bytes and time.
SELECT application_name,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_behind,
replay_lag
FROM pg_stat_replication;The replica-side timestamp grows on an idle primary even with no real lag; the primary-side byte diff is more reliable.
Traps
- Sending all SELECTs to replicas, including the read immediately after a write in the same request.
- Running long analytical queries on a hot-standby replica, which can delay replay or get cancelled due to conflicts.
- Assuming failover is lossless with asynchronous replication.
- Using replicas as backups; a bad DELETE replicates instantly, so you still need point-in-time recovery.
Constraints, idempotency and integrity in the database
Application validation runs in many processes that race with each other; constraints run in one place and cannot be bypassed. A unique constraint is the only reliable way to prevent duplicate signups or double charges under concurrency, because two check-then-insert requests can both pass the check. Foreign keys, CHECK constraints and NOT NULL catch bugs from scripts, backfills and services you do not own.
Idempotency builds on this: store a client-supplied key with a unique constraint and use INSERT ... ON CONFLICT so retries return the original result instead of creating a second row. This is how payment and webhook handlers stay correct when networks retry.
Constraints have costs worth naming. Foreign keys add a lookup on every child insert and a scan of the child table on parent deletes, which is why the referencing column usually needs its own index; PostgreSQL does not create it automatically, while InnoDB does. On very large sharded systems teams sometimes drop cross-shard foreign keys, but that should be a deliberate trade-off, not the default.
SQL
-- Tallyho payments: a client retrying a charge must not double-charge.
CREATE TABLE charges (
id bigserial PRIMARY KEY,
wallet_id bigint NOT NULL REFERENCES wallets(id),
idempotency_key text NOT NULL,
amount_cents integer NOT NULL CHECK (amount_cents > 0),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (wallet_id, idempotency_key)
);
CREATE INDEX idx_charges_wallet ON charges (wallet_id);
INSERT INTO charges (wallet_id, idempotency_key, amount_cents)
VALUES (552, 'req-7f3a91', 3000)
ON CONFLICT (wallet_id, idempotency_key) DO NOTHING
RETURNING id;
-- No row returned: this request was already processed; look it up and return it.The unique constraint, not application code, guarantees one charge per idempotency key.
Traps
- Checking for an existing row with SELECT and then inserting, which lets two concurrent requests both insert.
- Leaving foreign key columns unindexed in PostgreSQL, so deleting a parent row scans the entire child table.
- Using
ON CONFLICT DO NOTHINGand assuming RETURNING gives you the existing row; it returns nothing on conflict. - Storing money as floating point instead of integer cents or a numeric type.
Common questions
Short answers to the usual doubts.
Should I answer in terms of PostgreSQL or MySQL?
Pick the one you know best and say so up front, then mention differences where they change the answer, such as default isolation levels or automatic indexing of foreign keys. Interviewers value precise knowledge of one engine over vague claims about all of them.
How do I approach a vague 'the database is slow' scenario?
Start by narrowing it down: is it one query or everything, reads or writes, sudden or gradual? Then name what you would look at, such as slow query logs, pg_stat_activity for lock waits and connection counts, EXPLAIN ANALYZE on the worst query, and replica lag. Propose fixes only after the diagnosis.
Is Serializable isolation the safe default for correctness?
It gives the strongest guarantee, but it adds aborts under contention, and every transaction needs retry logic. Many teams stay on Read Committed and fix specific races with atomic updates, row locks or constraints. A good answer explains the trade-off rather than picking one level for everything.
When is denormalisation acceptable in production?
When a measured read path is too expensive to compute with joins and you can own the cost of keeping copies consistent, for example a cached order count updated in the same transaction as the insert. Mention how the copy stays correct and how you would detect drift.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Relational databases (SQL) in productionTake the test