Skip to content
Interview prep · questions

Databases interview questions

16 questions, from core to senior. Say your answer out loud first, then open the model answer and check it against the points a strong answer covers.

What is normalisation, and when would you denormalise a schema on purpose?

  • Core
Show the model answer

Normalisation means each fact is stored in one place. If a customer's email is in the customers table, the orders table holds only the customer ID, not a copy of the email. Then an update changes one row, and two copies can never disagree. In practice I aim for third normal form: every column depends on the key of its own table and on nothing else. Denormalising means I copy data on purpose to make reads cheaper. A common case is a count, such as the number of comments on a post, kept in a column so a list page does not count rows each time. Another case is a reporting table built from the main tables. The cost is that every copy must be kept in sync. So I denormalise only for a read I have measured to be slow, and I keep one table as the source of truth.

A strong answer covers

  • Defines normalisation: each fact is stored once, other tables refer to it by key
  • Names the problem it prevents: copies that disagree after an update
  • Gives a concrete reason to denormalise, such as a stored count for a hot read
  • Says the cost: every copy must be updated, in a transaction or by a job
  • Keeps one source of truth and denormalises only after measuring

Likely follow-up

How do you keep a stored comment count correct when many users comment at the same time?

When would you choose a relational database, and when a document store?

  • Core
Show the model answer

I start with a relational database, usually PostgreSQL, unless I have a clear reason not to. Most business data is related: users have orders, orders have items. A relational database joins that data, enforces constraints such as foreign keys, and gives transactions across many tables. A document store keeps each record as one JSON-like document. It fits well when the data is read and written as a whole, for example a product with attributes that differ between categories, and when I rarely need to join documents. The schema is flexible, but the rules move into the application code, and every reader must handle old shapes of the document. PostgreSQL also has a jsonb column type with indexes, so I can keep flexible attributes in one column and still use SQL for the rest. The deciding question is how the data will be queried, not how it looks today.

A strong answer covers

  • Defaults to a relational database for related business data
  • Names what SQL gives: joins, constraints and multi-table transactions
  • Gives a good fit for documents: data read and written as a whole, few joins
  • Says a flexible schema moves the rules into application code
  • Mentions jsonb in PostgreSQL as a middle path

Likely follow-up

Your product needs a report that joins data from many document types. What do you do?

You add read replicas. A user saves their profile, reloads, and sees the old data. What happened?

  • Core
Show the model answer

This is replication lag. The write went to the primary, and the reload read from a replica that had not received the change yet. In PostgreSQL, streaming replication is asynchronous by default, so a replica can be behind by milliseconds or, under heavy load, by much longer. Replicas help when reads are much more frequent than writes, but every read from a replica can be a little old. So I decide per query. Reads that must see the user's own write go to the primary. A simple rule is: after a user writes, send that user's reads to the primary for a short time. Pages where a few seconds of delay is fine, such as a public list or a report, go to replicas. I also monitor the lag, and I take a replica out of rotation when it falls too far behind.

A strong answer covers

  • Names replication lag: the replica has not applied the write yet
  • Says PostgreSQL replication is asynchronous by default
  • Gives a read-your-writes fix: send that user's reads to the primary for a while
  • Decides per query which reads can be slightly old
  • Monitors lag and removes a replica that falls behind

Likely follow-up

What changes if you make replication synchronous, and what does it cost?

Why does the first query get slow on deep pages, and how does the second one fix it?

  • Core
-- Page 5000, offset style
SELECT id, title, created_at FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 100000;

-- Keyset style: start after the last row of the previous page
SELECT id, title, created_at FROM posts
WHERE (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 20;
Show the model answer

With OFFSET, the database still reads the 100,000 skipped rows and throws them away, so each deeper page costs more. Offset also breaks when the data changes: if a new post arrives while the user reads, every row moves down by one, and the next page shows a row again. Keyset pagination, also called cursor pagination, remembers the last row the user saw and asks for the rows after it. With an index on created_at and id, the database jumps straight to that point in the index and reads 20 rows, however deep the page is. The id is in the sort as a tie breaker, because two posts can have the same created_at. The API returns an opaque cursor that encodes those two values. The cost is that the user cannot jump to page 5000 directly, only go to the next or the previous page. For most feeds and APIs that is fine.

A strong answer covers

  • Says OFFSET reads and discards the skipped rows, so deep pages are slow
  • Says OFFSET skips or repeats rows when data is inserted between pages
  • Explains keyset: filter after the last seen values, using an index
  • Adds a unique tie breaker such as id to the sort order
  • Names the trade-off: no jump to an arbitrary page number

Likely follow-up

How do you support a previous-page link with keyset pagination?

These two transactions run at the same time and one fails with a deadlock error. Why, and how do you avoid it?

  • Core
-- Transaction A: transfer from account 1 to account 2
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT;

-- Transaction B: transfer from account 2 to account 1
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 2;
UPDATE accounts SET balance = balance + 30 WHERE id = 1;
COMMIT;
Show the model answer

Each UPDATE locks its row until the transaction ends. A locks row 1, and B locks row 2. Then A waits for row 2, which B holds, and B waits for row 1, which A holds. Neither can continue. PostgreSQL checks for this after a short wait, picks one transaction, and aborts it with a deadlock error, so the other one can finish. The main fix is to take locks in the same order everywhere. Here I update the account with the lower ID first, whatever the direction of the transfer. Then the second transaction waits for the first one instead of forming a cycle. I also keep transactions short, and I never wait for a network call while holding locks. Deadlocks can still happen in rare cases, so the code treats the error as safe to retry: it runs the whole transaction again, a limited number of times.

A strong answer covers

  • Explains the cycle: each transaction holds a lock the other one needs
  • Says the database detects it and aborts one transaction
  • Fixes it by locking rows in one consistent order, such as by ID
  • Keeps transactions short, with no slow calls while locks are held
  • Retries the whole transaction after a deadlock error

Likely follow-up

How would you find which queries are involved in deadlocks in production?

This query runs on every page load. Which index would you create for it, and why in that column order?

  • Core
SELECT created_at, total
FROM orders
WHERE customer_id = :customer AND status = 'paid'
ORDER BY created_at DESC
LIMIT 10;
Show the model answer

I would create an index on customer_id, status and created_at, in that order. The rule is: columns compared with equality go first, then the column used for a range or for sorting. With customer_id and status fixed, the matching entries in the index are already sorted by created_at. So the database reads the first 10 entries and stops, with no sort step. If created_at were first, the index could not narrow the search by customer. In PostgreSQL I can also add INCLUDE (total). Then the index holds every column the query needs, and the plan can be an index-only scan that does not visit the table at all. That is a covering index. Index-only scans work best when the table is vacuumed often, because PostgreSQL must know that a page has no recent changes. Each extra column makes the index bigger and writes slower, so I cover only the hottest queries.

A strong answer covers

  • Puts equality columns first, then the sort or range column
  • Explains that the index then returns rows already in the right order
  • Defines a covering index: it holds every column the query needs
  • Mentions INCLUDE in PostgreSQL and an index-only scan
  • Weighs the cost: a bigger index and slower writes

Likely follow-up

The query also needs to filter by a date range. Where does that column go?

What is connection pooling, and why does a PostgreSQL database need it?

  • Core
Show the model answer

Opening a database connection is expensive. In PostgreSQL each connection is a separate server process with its own memory, so the server allows only a limited number, set by max_connections. A pool keeps a few connections open and lends one to each request, which gives it back when it is done. Most drivers have a pool in the application. The problem comes with many app instances: ten servers with a pool of twenty each already need two hundred connections. Serverless functions are worse, because each one can open its own. Then I put a pooler such as PgBouncer between the app and the database. In transaction mode it gives a server connection to a client only for one transaction, so many clients share a few connections. The catch is that session features, such as SET or session advisory locks, do not carry over between transactions. I size the pool small, because more connections than CPU cores rarely makes the database faster.

A strong answer covers

  • Says a connection is costly: a process per connection in PostgreSQL
  • Explains the pool: open connections are reused across requests
  • Does the math for many app instances or serverless functions
  • Names an external pooler such as PgBouncer and its transaction mode
  • Knows the catch: session state does not survive in transaction mode

Likely follow-up

Requests start timing out while waiting for a connection from the pool. How do you find the cause?

Your code checks that an email is not taken before it inserts a user. Why is that not enough?

  • Core
Show the model answer

Because there is a race. Two signup requests with the same email both run the check, both see no user, and both insert. A check in the application cannot see a row that another request is about to write. A unique constraint in the database closes that gap: the second insert fails, and I catch the unique violation and tell the user the email is taken. The database is the one place every writer passes through, including scripts, other services and manual fixes. So I put the rules that must always hold there. A foreign key stops an order that points to a missing user. A check constraint stops a negative quantity. NOT NULL stops a missing value. I still validate in the application, because it gives clear error messages early. But the application check is for the user's experience, and the constraint is the guarantee.

A strong answer covers

  • Explains the race: two requests both pass the check, then both insert
  • Uses a unique constraint and handles the unique violation error
  • Says the database is the one place every writer goes through
  • Names foreign key, check and NOT NULL constraints with examples
  • Keeps application validation for clear messages, not as the guarantee

Likely follow-up

Emails are case insensitive. How do you make the unique rule respect that?

What is a soft delete, and what problems does it bring?

  • Core
Show the model answer

A soft delete does not remove the row. It sets a column such as deleted_at, and the application hides rows where that column is set. It makes undo easy, and the history stays. But it has real costs. Every query must remember to filter out deleted rows, and one forgotten filter shows deleted data to users. Unique rules break: a user deletes an account, and a new signup with the same email fails, because the old row still holds it. In PostgreSQL I fix that with a partial unique index that covers only rows where deleted_at is null. Foreign keys no longer protect me, because a deleted parent still exists for the database. The table keeps growing. And a privacy request to erase someone's data needs a real delete anyway. So I use soft delete only where undo or history matters. Otherwise I hard delete, and copy the row to an archive table first if I need a record.

A strong answer covers

  • Defines it: a deleted_at column instead of removing the row
  • Says every query must filter, and a missed filter leaks data
  • Explains the unique constraint problem and the partial unique index fix
  • Mentions privacy erasure, which needs a real delete
  • Offers an alternative: hard delete plus an archive table

Likely follow-up

How would you make sure no query forgets the deleted_at filter?

Someone runs a DELETE without a WHERE clause on production at 14:05. How do you get the data back?

  • Core
Show the model answer

A read replica does not help here, because it copied the DELETE within seconds. I need point-in-time recovery. In PostgreSQL that is built from two parts: a physical base backup taken regularly, and an archive of the write-ahead log, the WAL, which records every change after it. To recover, I restore the latest base backup to a new server and replay the WAL up to a target time, here just before 14:05. Then I copy the lost rows back into production, or switch over to the restored server. I restore to a new server, not over production, so other good writes made after 14:05 are not lost. A plain pg_dump is also useful, but it only gives me the moment the dump ran. Most important, a backup I have never restored is not a backup. I test the restore on a schedule, and I measure how long it takes.

A strong answer covers

  • Says a replica is not a backup: it copies the mistake
  • Explains point-in-time recovery: a base backup plus archived WAL
  • Restores to a new server and replays up to just before the mistake
  • Compares it with a logical dump, which has only one moment
  • Tests restores on a schedule and knows how long one takes

Likely follow-up

How much data can you lose and how long can you be down? Who decides those numbers?

Which column types do you use for a price and for the time of a payment, and why?

  • Core
CREATE TABLE payments (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  amount numeric(12, 2) NOT NULL,
  currency char(3) NOT NULL,
  paid_at timestamptz NOT NULL DEFAULT now()
);
Show the model answer

For money I never use a float. A float stores numbers in binary, so a value like 0.1 is not exact, and small errors add up in sums. I use an exact decimal type, numeric in PostgreSQL, or an integer count of the smallest unit, such as cents. I always store the currency next to the amount, because 100 means nothing alone, and some currencies have no minor unit. For time I use timestamptz in PostgreSQL. It stores an exact instant, kept internally in UTC, and shows it in the time zone of the session. The type without a time zone stores only a clock reading, so the same value means different instants in different places. There is one exception: a future event in local time, like a meeting at 9:00 in a given city. For that I store the local time and the time zone name, because time zone rules can change before the date.

A strong answer covers

  • Rejects floats for money because binary fractions are not exact
  • Uses numeric or an integer of minor units, with the currency stored beside it
  • Uses timestamptz for instants and explains what it stores
  • Explains why a timestamp without time zone is ambiguous
  • Stores future local events as local time plus a time zone name

Likely follow-up

How do you split a payment of 100.00 into three parts without losing a cent?

What are the transaction isolation levels, and which anomaly does each one prevent?

  • Senior
Show the model answer

The SQL standard defines four levels by the anomalies they allow. Read Uncommitted allows dirty reads, which means seeing another transaction's uncommitted changes. PostgreSQL never allows that, and treats Read Uncommitted as Read Committed. Read Committed, the PostgreSQL default, shows only committed data, but each statement takes a new snapshot. So the same SELECT run twice can return different rows. Repeatable Read keeps one snapshot for the whole transaction. In PostgreSQL that also prevents phantom rows, but it still allows write skew. For example, two doctors both read that two are on call, and each one signs off, leaving none. Serializable prevents that too. The result is as if the transactions ran one after another. PostgreSQL does this by aborting one transaction with a serialization error when it finds a conflict. So at Repeatable Read and Serializable, my code must be ready to retry the whole transaction. I use Read Committed with explicit locks or constraints in most code, and Serializable where the rules span many rows.

A strong answer covers

  • Names the four levels and the anomaly each one allows
  • Says PostgreSQL's default is Read Committed and it never shows dirty reads
  • Explains write skew with a concrete example
  • Says Serializable in PostgreSQL aborts conflicting transactions
  • Retries the whole transaction on a serialization error

Likely follow-up

How else could you prevent the on-call problem without the Serializable level?

How do you rename a column in a busy production table without downtime?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes

A query became slow. Here is the output of EXPLAIN ANALYZE. What does it tell you, and what do you do?

  • Senior
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;

Seq Scan on orders  (cost=0.00..18334.00 rows=5 width=48)
                    (actual time=0.031..92.410 rows=3 loops=1)
  Filter: (customer_id = 42)
  Rows Removed by Filter: 999997
Planning Time: 0.080 ms
Execution Time: 92.440 ms

The model answer to this senior question opens with a year in the app. What a year includes

What is the difference between partitioning and sharding, and when do you need each?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes

How does PostgreSQL let readers and writers work at the same time, and why can a table grow even when the row count stays the same?

  • Senior

The model answer to this senior question opens with a year in the app. What a year includes