Databases Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What data structure does a default PostgreSQL index use?
Correct answer: A B-tree
B-trees keep keys sorted, so they support equality, ranges (
<,BETWEEN), sorting and prefixLIKE 'abc%'(with the right collation or operator class). Hash, GIN, GiST and BRIN are for special cases.2. There's an index on
(last_name, first_name). Which query can use it efficiently?Correct answer:
WHERE last_name = 'Smith'A composite index is sorted by the first column, then by the second within it, like a phone book. It helps queries on a leading prefix of its columns; searching only by
first_nameusually can't use it well.3. There's an index on
created_at. Why mightWHERE date(created_at) = '2026-11-01'ignore it?Correct answer: The function hides the raw column from the index
Rewrite as
created_at >= '2026-11-01' AND created_at < '2026-11-02', or create an index on the expression itself.4. Why can't a normal B-tree index speed up
WHERE name LIKE '%son'?Correct answer: With a leading wildcard the value's start is unknown
LIKE 'son%'can use a B-tree (with a suitable operator class). For substring or fuzzy search use a trigram GIN index (pg_trgm) or full-text search.5. What is a partial index?
CREATE INDEX ON orders (created_at) WHERE status = 'pending';Correct answer: An index on only the rows matching a condition
It's great when queries always filter on a rare value. A partial unique index can also enforce rules like 'one active subscription per user'.
6. What is a covering index and an index-only scan?
Correct answer: The index alone answers the query, no table read
Index-only scans also depend on the visibility map, so tables with many recent changes still need some heap reads.
VACUUMkeeps the map up to date.7. Why might PostgreSQL choose a sequential scan even though an index exists?
Correct answer: For a large share of rows, sequential reads are cheaper
The planner estimates costs from statistics. For low-selectivity conditions (e.g.
status = 'active'matching 90% of rows) a seq scan is the right choice.8. What does
CREATE INDEX CONCURRENTLYgive you?Correct answer: It builds the index without blocking writes
A plain
CREATE INDEXblocks inserts, updates and deletes until it finishes, which can mean downtime on a big table.CONCURRENTLYcan't run inside a transaction block.9. Which index type fits searching inside a
jsonbcolumn, likeWHERE data @> '{"tags": ["sale"]}'?Correct answer: GIN
GIN indexes the keys and elements inside a value. It's also used for arrays and full-text search. BRIN suits huge tables whose values follow physical order, like timestamps in logs.
10. Why can random UUIDs (v4) as primary keys slow down inserts on large tables?
Correct answer: New keys land on random pages, causing splits
Time-ordered IDs (UUID v7, ULID or
bigintidentity) append to the end of the index, keeping the hot part small and in memory.11. What is the difference between
EXPLAINandEXPLAIN ANALYZE?Correct answer:
EXPLAIN ANALYZEactually runs the queryBecause
ANALYZEruns the query, wrap data-changing statements inBEGIN ... ROLLBACK. AddBUFFERSto see how much data was read.12. In
EXPLAIN ANALYZEthe planner estimated 10 rows but got 500,000. What does it suggest?Correct answer: Outdated statistics; run
ANALYZEBad estimates lead to bad plans, like a nested loop over half a million rows. Correlated columns may need extended statistics (
CREATE STATISTICS).13. Which join algorithms can PostgreSQL use?
Correct answer: Nested loop, hash join and merge join
Nested loops suit small inputs with an index on the inner side, hash joins suit large unsorted inputs, merge joins suit inputs already sorted on the join key.
14. Why can
SELECT COUNT(*) FROM big_tablebe slow in PostgreSQL?Correct answer: With MVCC, it must scan to count visible rows
If an approximate number is enough, read the estimate from
pg_class.reltuples, or keep a counter updated by the application or a trigger.15. How do you find the queries that consume the most total time in production?
Correct answer: With the
pg_stat_statementsextensionA query taking 5 ms but running a million times a day can matter more than one slow report. Sort by total time, then optimize the top entries.
16. What is PostgreSQL's default transaction isolation level?
Correct answer: Read Committed
Each statement sees data committed before that statement started. Two statements in one transaction can therefore see different data.
17. What is a 'non-repeatable read'?
Correct answer: The same row read twice gives different values
It's possible under Read Committed. Repeatable Read gives the whole transaction one snapshot, so repeated reads return the same data.
18. What is a 'lost update', and how can you prevent it?
-- Two requests at the same time: SELECT balance FROM accounts WHERE id = 1; -- both read 100 UPDATE accounts SET balance = 150 WHERE id = 1; -- +50 UPDATE accounts SET balance = 130 WHERE id = 1; -- +30Correct answer: One change overwrites another; use an atomic update
Read-modify-write in application code is the classic source. Let the database do the arithmetic, or lock or version the row.
19. What does
SELECT ... FOR UPDATEdo?Correct answer: Locks the selected rows until the transaction ends
Other writers wait. Keep such transactions short, and lock rows in a consistent order to avoid deadlocks.
20. What is a deadlock, and what does PostgreSQL do about it?
Correct answer: Two transactions wait on each other; one is aborted
The aborted transaction should be retried. Prevent deadlocks by locking rows in the same order everywhere and keeping transactions short.
21. How does optimistic locking work?
Correct answer: Updates check a row version and fail if it changed
No locks are held while the user thinks, which suits web forms. Under heavy contention many retries happen, and pessimistic locking may be better.
22. What does
INSERT ... ON CONFLICT (email) DO UPDATEdo?Correct answer: An atomic upsert: insert, or update on a key conflict
It's safe under concurrency, unlike 'select, then insert or update'.
DO NOTHINGsimply skips duplicates. The conflict target needs a unique index.23. Why are long-running transactions harmful in PostgreSQL?
Correct answer: They hold locks and block VACUUM cleanup
Don't keep a transaction open while calling external APIs or waiting for user input. Monitor
pg_stat_activityfor 'idle in transaction' sessions.24. What is a savepoint?
Correct answer: A marker in a transaction to roll back to
SAVEPOINT s; ... ROLLBACK TO s;undoes only the work since the savepoint. ORMs use savepoints for nested transactions.25. What does a window function like
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)do?Correct answer: Numbers rows per user, without collapsing them
Filter
WHERE rn = 1in an outer query to get each user's latest order. Window functions also compute running totals, ranks and moving averages.26. What is the difference between
RANK()andDENSE_RANK()?Correct answer: With ties,
RANK()leaves gaps in numbersROW_NUMBER()gives every row a unique number even for ties, in an order you should make deterministic with extra sort columns.27. How do you compute a running total of payments per user?
Correct answer:
SUM(amount) OVER (PARTITION BY user_id ORDER BY paid_at)With
ORDER BYinsideOVER, the window by default goes from the start of the partition to the current row (including rows with the same sort value).28. What is a CTE (
WITH ...) good for?WITH recent AS ( SELECT * FROM orders WHERE created_at > now() - interval '7 days' ) SELECT user_id, COUNT(*) FROM recent GROUP BY user_id;Correct answer: Naming a subquery for readability and recursion
Since PostgreSQL 12, simple CTEs are inlined into the main query and optimized together.
MATERIALIZEDforces computing the CTE once.29. What does
WITH RECURSIVElet you do?Correct answer: Query hierarchies of unknown depth, like a tree
A recursive CTE has a base part and a part that refers to the CTE itself, repeated until no new rows appear. Guard against cycles in the data.
30. Why can
WHERE id NOT IN (SELECT user_id FROM bans)return no rows at all?Correct answer: A NULL from the subquery makes
NOT INnever truex NOT IN (1, NULL)meansx <> 1 AND x <> NULL, and the second part is unknown. This is a classic bug with nullable columns.31. What does
LEFT JOIN LATERALallow?SELECT u.name, o.* FROM users u LEFT JOIN LATERAL ( SELECT * FROM orders WHERE orders.user_id = u.id ORDER BY created_at DESC LIMIT 3 ) o ON true;Correct answer: A
FROMsubquery that references earlier tablesIt's a clean way to write 'top N per group'. With an index on
(user_id, created_at)each lookup is cheap.32. What is
COUNT(*) FILTER (WHERE status = 'paid')used for?Correct answer: Counting only matching rows inside an aggregate
For example
COUNT(*) FILTER (WHERE status = 'paid') AS paid, COUNT(*) FILTER (WHERE status = 'new') AS newin a single pass.33. When should you use
jsonbcolumns in PostgreSQL?Correct answer: For flexible, rarely queried attributes
Regular columns get types, constraints, foreign keys and better statistics.
jsonbis binary and indexable with GIN, unlike text-basedjson.34. What does PostgreSQL full-text search give you compared with
ILIKE '%word%'?Correct answer: Stemming, ranking and fast GIN indexes
to_tsvector('english', body) @@ to_tsquery('running')matches 'run' and 'runs'. For typo tolerance and facets, dedicated engines like Elasticsearch or Meilisearch go further.35. What is the N+1 query problem?
Correct answer: One list query plus one more query per item
Fix it with a join,
WHERE id = ANY($1)orIN (...)for all IDs at once, or the ORM's eager loading (include,with).36. Why is keyset (cursor) pagination faster than
OFFSETfor deep pages?SELECT * FROM posts WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20;Correct answer: It seeks by index instead of discarding earlier rows
Include a unique column (like
id) as a tiebreaker. The trade-off: no jumping to an arbitrary page number.37. Why do applications use a connection pool?
Correct answer: Connections are expensive, so a pool reuses them
max_connectionsis limited, and each connection uses memory. Many app instances or serverless functions often need an external pooler like PgBouncer.38. How do you add a
NOT NULLcolumn with a default to a huge table without long locks in modern PostgreSQL?Correct answer: Since PostgreSQL 11 it's a fast metadata-only change
Volatile defaults like
random()still rewrite the table. For computed values, add a nullable column, backfill in batches, then add the constraint.39. What is a safe way to rename a column used by a running application?
Correct answer: Expand and contract: add, write both, switch, drop
During a rolling deploy old and new code run together, so every schema change must work with both versions.
40. What is a materialized view?
Correct answer: A stored query result that must be refreshed
Good for heavy reports and dashboards.
REFRESH ... CONCURRENTLY(needs a unique index) lets reads continue during the refresh.41. What is a common downside of putting business logic in triggers?
Correct answer: Logic gets hidden, harder to test and debug
Triggers are fine for things that must always happen at the data level, like audit logs or
updated_at. Complex rules are usually clearer in the application.42. What does Row-Level Security (RLS) in PostgreSQL do?
Correct answer: Filters the rows each role can see
Services like Supabase rely on it: policies such as
user_id = auth.uid()protect data even if a query forgets to filter.43. Where should a 'unique email' rule be enforced?
Correct answer: In the database, with a unique constraint
Two requests can both pass a 'does it exist?' check and insert duplicates. The constraint makes the database the final judge; handle its error in the app.
44. How do you insert 10,000 rows efficiently?
Correct answer: A multi-row
INSERTorCOPYin one transactionEach autocommit waits for a disk flush, and each statement costs a round trip. Batching cuts both.
45. What does MVCC mean in PostgreSQL?
Correct answer: Updates create row versions, so reads don't block writes
Each transaction sees a snapshot. Old row versions remain until VACUUM removes them once no transaction can see them.
46. What does VACUUM do?
Correct answer: Reclaims space from dead row versions for reuse
Autovacuum runs it automatically. Regular
VACUUMdoesn't shrink the file;VACUUM FULLdoes but locks the table.47. Why does an
UPDATEin PostgreSQL write a whole new row version?Correct answer: MVCC: earlier transactions still need the old version
That's why frequently updated wide rows cause bloat. HOT updates avoid touching indexes when no indexed column changes and the page has free space.
48. In MongoDB, when should related data be embedded in one document rather than referenced?
Correct answer: When it's read together and stays bounded in size
Reference data that grows without limit (all comments of a popular post) or is shared by many documents. MongoDB documents are limited to 16 MB.
49. What is MongoDB's aggregation pipeline?
Correct answer: A sequence of stages that transform documents
Put
$matchearly so indexes can be used and fewer documents flow through later stages.50. Does MongoDB support multi-document transactions?
Correct answer: Yes, on replica sets and sharded clusters
Single-document writes are always atomic. Multi-document transactions add overhead and have time limits, so don't model data as if it were relational.
51. Which Redis data type fits a leaderboard?
Correct answer: Sorted set (
ZADD,ZRANGE)Sorted sets keep members ordered by score with O(log n) updates. Hashes suit objects, lists suit queues, sets suit unique membership.
52. What is the hardest part of caching database results?
Correct answer: Invalidation: updating data when the source changes
Common approaches: short TTLs, deleting keys on write, or versioned keys. Always decide how stale the data may be.
53. What happens when Redis reaches its
maxmemorylimit?Correct answer: It applies the configured eviction policy
For a cache, LRU or LFU eviction is typical. For data you can't lose (queues, locks), eviction is dangerous, so use
noevictionor a separate instance.54. What is a key difference between SQL and NoSQL scaling, as usually described?
Correct answer: Many NoSQL systems partition across nodes by design
The line is blurry now: Citus, CockroachDB and others shard SQL, and NoSQL systems add transactions. Choose by data model and access patterns.
55. What is third normal form (3NF), roughly?
Correct answer: Non-key columns depend only on the key
If
ordersstorescustomer_idandcustomer_city, the city depends on the customer, not the order, so it belongs incustomers.56. How would you store a user's changing subscription plans so you can see the history?
Correct answer: A separate table of plan periods with valid dates
History tables make questions like 'what plan did they have on March 1?' easy. PostgreSQL range types and exclusion constraints can prevent overlapping periods.
57. What is polymorphic association, and what's its problem?
Correct answer: One column pair pointing at many tables, with no FK
Alternatives: separate nullable foreign keys with a
CHECKthat exactly one is set, or a separate junction table per parent type.58. How should tags on articles usually be stored in a relational database?
Correct answer: A
tagstable plus anarticle_tagsjunction tableThe junction table supports renaming tags, counting usage and foreign keys. Arrays are simpler when tags are just labels without their own data.
59. Why store an order's price at purchase time instead of always joining to the current product price?
Correct answer: Prices change; keep what the customer actually paid
This isn't harmful duplication: it's a different fact (the historical price). The same goes for addresses on invoices.
60. What is a read replica used for?
Correct answer: Serving reads from a copy to offload the primary
Replicas usually lag a bit behind. Reading your own write from a replica right after writing may return old data.
61. What is point-in-time recovery (PITR)?
Correct answer: Replaying WAL up to a chosen moment
It requires continuous WAL archiving. Managed services offer it out of the box with a retention window.
62. Why can
ALTER TABLEon a busy table freeze the whole application?Correct answer: Its lock queue blocks every new query on the table
Set
lock_timeoutin migrations so the change fails fast instead of queuing everyone, and retry later.63. What is a database seed used for?
Correct answer: Filling a database with initial or sample data
Keep seeds idempotent (e.g. upserts) so they can run repeatedly. Never mix test data into production seeds.
64. Why are integration tests against a real database (e.g. in Docker) often preferred over mocking the database?
Correct answer: They catch real SQL errors mocks would hide
Run each test in a transaction that rolls back, or reset the schema, so tests stay isolated. Testcontainers makes this convenient.
65. What is a 'phantom read'?
Correct answer: A repeated query returns newly committed rows
The SQL standard allows phantoms under Repeatable Read, but PostgreSQL's Repeatable Read uses a snapshot and doesn't show them.
66. What must an application do when using the Serializable isolation level in PostgreSQL?
Correct answer: Retry transactions failing with a serialization error
PostgreSQL detects dangerous patterns and aborts one transaction instead of blocking. A retry loop around the whole transaction is required.
67. What does
SELECT DISTINCT ON (user_id) * FROM orders ORDER BY user_id, created_at DESCreturn?Correct answer: One row per user: here, their latest order
DISTINCT ONis a PostgreSQL extension for 'latest per group'. TheORDER BYmust start with theDISTINCT ONcolumns.68. What does
GROUP BY ROLLUP (country, city)add to the result?Correct answer: Subtotals per country and a grand total
In subtotal rows the rolled-up columns are NULL;
GROUPING()tells them apart from real NULLs.CUBEandGROUPING SETSgive other combinations.69. What is a generated column?
ALTER TABLE users ADD COLUMN email_lower text GENERATED ALWAYS AS (lower(email)) STORED;Correct answer: A column computed from others in the same row
It can be indexed and can't get out of sync. Since PostgreSQL 18 generated columns can also be virtual (computed on read).
70. What are trade-offs of using a PostgreSQL
ENUMtype for a status column?Correct answer: Compact and safe, but awkward to change values
Adding enum values is easy; removing them requires recreating the type. A lookup table can also store extra data like labels or sort order.
71. Why can
ORDER BY created_at DESC LIMIT 10be very fast on a huge table?Correct answer: With an index, it reads 10 entries and stops
Without a suitable index the database must read and sort everything, then return 10 rows. Add the filter columns first in the index when there's a
WHERE.72. What is a 'Bitmap Heap Scan' in an
EXPLAINplan?Correct answer: Collects row locations in a bitmap, then reads pages in order
It sits between an index scan and a seq scan: good for medium selectivity, and it can combine several indexes with AND/OR.
73. What does
statement_timeoutprotect against?Correct answer: Runaway queries: long statements get cancelled
Set it per role or per session for web traffic, e.g. a few seconds.
idle_in_transaction_session_timeouthandles forgotten open transactions.74. Why is Redis
INCRa good fit for a simple rate limiter?Correct answer: It increments atomically across concurrent requests
Redis runs commands one at a time, so
INCRhas no race. Use a Lua script orSET ... NX EXto set the TTL safely together with the first increment.75. What does a foreign key with
ON DELETE RESTRICT(or the defaultNO ACTION) do when you delete a referenced row?Correct answer: The delete fails while rows still reference it
It protects against orphaned rows.
NO ACTIONcan be deferred to the end of the transaction withDEFERRABLE,RESTRICTcannot.