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. 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 prefix LIKE 'abc%' (with the right collation or operator class). Hash, GIN, GiST and BRIN are for special cases.

  2. 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_name usually can't use it well.

  3. 3. There's an index on created_at. Why might WHERE 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. 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. 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. 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. VACUUM keeps the map up to date.

  7. 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. 8. What does CREATE INDEX CONCURRENTLY give you?

    Correct answer: It builds the index without blocking writes

    A plain CREATE INDEX blocks inserts, updates and deletes until it finishes, which can mean downtime on a big table. CONCURRENTLY can't run inside a transaction block.

  9. 9. Which index type fits searching inside a jsonb column, like WHERE 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. 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 bigint identity) append to the end of the index, keeping the hot part small and in memory.

  11. 11. What is the difference between EXPLAIN and EXPLAIN ANALYZE?

    Correct answer: EXPLAIN ANALYZE actually runs the query

    Because ANALYZE runs the query, wrap data-changing statements in BEGIN ... ROLLBACK. Add BUFFERS to see how much data was read.

  12. 12. In EXPLAIN ANALYZE the planner estimated 10 rows but got 500,000. What does it suggest?

    Correct answer: Outdated statistics; run ANALYZE

    Bad estimates lead to bad plans, like a nested loop over half a million rows. Correlated columns may need extended statistics (CREATE STATISTICS).

  13. 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. 14. Why can SELECT COUNT(*) FROM big_table be 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. 15. How do you find the queries that consume the most total time in production?

    Correct answer: With the pg_stat_statements extension

    A 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. 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. 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. 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;  -- +30

    Correct 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. 19. What does SELECT ... FOR UPDATE do?

    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. 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. 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. 22. What does INSERT ... ON CONFLICT (email) DO UPDATE do?

    Correct answer: An atomic upsert: insert, or update on a key conflict

    It's safe under concurrency, unlike 'select, then insert or update'. DO NOTHING simply skips duplicates. The conflict target needs a unique index.

  23. 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_activity for 'idle in transaction' sessions.

  24. 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. 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 = 1 in an outer query to get each user's latest order. Window functions also compute running totals, ranks and moving averages.

  26. 26. What is the difference between RANK() and DENSE_RANK()?

    Correct answer: With ties, RANK() leaves gaps in numbers

    ROW_NUMBER() gives every row a unique number even for ties, in an order you should make deterministic with extra sort columns.

  27. 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 BY inside OVER, the window by default goes from the start of the partition to the current row (including rows with the same sort value).

  28. 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. MATERIALIZED forces computing the CTE once.

  29. 29. What does WITH RECURSIVE let 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. 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 IN never true

    x NOT IN (1, NULL) means x <> 1 AND x <> NULL, and the second part is unknown. This is a classic bug with nullable columns.

  31. 31. What does LEFT JOIN LATERAL allow?

    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 FROM subquery that references earlier tables

    It's a clean way to write 'top N per group'. With an index on (user_id, created_at) each lookup is cheap.

  32. 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 new in a single pass.

  33. 33. When should you use jsonb columns in PostgreSQL?

    Correct answer: For flexible, rarely queried attributes

    Regular columns get types, constraints, foreign keys and better statistics. jsonb is binary and indexable with GIN, unlike text-based json.

  34. 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. 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) or IN (...) for all IDs at once, or the ORM's eager loading (include, with).

  36. 36. Why is keyset (cursor) pagination faster than OFFSET for 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. 37. Why do applications use a connection pool?

    Correct answer: Connections are expensive, so a pool reuses them

    max_connections is limited, and each connection uses memory. Many app instances or serverless functions often need an external pooler like PgBouncer.

  38. 38. How do you add a NOT NULL column 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. 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. 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. 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. 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. 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. 44. How do you insert 10,000 rows efficiently?

    Correct answer: A multi-row INSERT or COPY in one transaction

    Each autocommit waits for a disk flush, and each statement costs a round trip. Batching cuts both.

  45. 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. 46. What does VACUUM do?

    Correct answer: Reclaims space from dead row versions for reuse

    Autovacuum runs it automatically. Regular VACUUM doesn't shrink the file; VACUUM FULL does but locks the table.

  47. 47. Why does an UPDATE in 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. 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. 49. What is MongoDB's aggregation pipeline?

    Correct answer: A sequence of stages that transform documents

    Put $match early so indexes can be used and fewer documents flow through later stages.

  50. 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. 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. 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. 53. What happens when Redis reaches its maxmemory limit?

    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 noeviction or a separate instance.

  54. 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. 55. What is third normal form (3NF), roughly?

    Correct answer: Non-key columns depend only on the key

    If orders stores customer_id and customer_city, the city depends on the customer, not the order, so it belongs in customers.

  56. 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. 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 CHECK that exactly one is set, or a separate junction table per parent type.

  58. 58. How should tags on articles usually be stored in a relational database?

    Correct answer: A tags table plus an article_tags junction table

    The junction table supports renaming tags, counting usage and foreign keys. Arrays are simpler when tags are just labels without their own data.

  59. 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. 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. 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. 62. Why can ALTER TABLE on a busy table freeze the whole application?

    Correct answer: Its lock queue blocks every new query on the table

    Set lock_timeout in migrations so the change fails fast instead of queuing everyone, and retry later.

  63. 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. 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. 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. 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. 67. What does SELECT DISTINCT ON (user_id) * FROM orders ORDER BY user_id, created_at DESC return?

    Correct answer: One row per user: here, their latest order

    DISTINCT ON is a PostgreSQL extension for 'latest per group'. The ORDER BY must start with the DISTINCT ON columns.

  68. 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. CUBE and GROUPING SETS give other combinations.

  69. 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. 70. What are trade-offs of using a PostgreSQL ENUM type 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. 71. Why can ORDER BY created_at DESC LIMIT 10 be 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. 72. What is a 'Bitmap Heap Scan' in an EXPLAIN plan?

    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. 73. What does statement_timeout protect 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_timeout handles forgotten open transactions.

  74. 74. Why is Redis INCR a good fit for a simple rate limiter?

    Correct answer: It increments atomically across concurrent requests

    Redis runs commands one at a time, so INCR has no race. Use a Lua script or SET ... NX EX to set the TTL safely together with the first increment.

  75. 75. What does a foreign key with ON DELETE RESTRICT (or the default NO ACTION) do when you delete a referenced row?

    Correct answer: The delete fails while rows still reference it

    It protects against orphaned rows. NO ACTION can be deferred to the end of the transaction with DEFERRABLE, RESTRICT cannot.