Courses / Databases for Backend Interviews / Chapter 1
Module 1 · Start here · Chapter 1 of 27
The Database Interview: Rounds, Scoring and a Study Plan
Start here. Next up: Before Databases: What Goes Wrong with Plain Files.
Part 1 · The three kinds of database question
Where databases come up
Questions about databases come in three different shapes, and each one rewards a different kind of preparation.
The formats vary from company to company and from year to year, and this course makes no claim about any particular employer. What it does is describe the skills behind each shape, which stay the same whatever the format. If you know what a shape tests, you can recognise it when it shows up in a new form.
The three shapes are a live SQL question, a schema design question, and a question about how a database works inside a backend or system design discussion. The first is about writing queries. The second is about modelling data. The third is about understanding what the database does with your queries and your data once they arrive.
The live SQL question
In the form this course prepares you for, you are given a few tables, described in words or as a diagram, and a question that the data should answer: the top three products per city, customers who ordered in March and not in April, the longest streak of consecutive order days. You write a query, talk through it, and check it against a small sample by hand.
This shape tests fluency in a handful of patterns. The patterns are the ones this course teaches in its SQL chapters: counting and bucketing, existence and exclusion, top-N per group, comparing a row with its neighbour or its group, streaks and sessions, recursion over a tree, and reshaping. A candidate who has met each pattern before recognises the shape of the question in the first minute and spends the rest of the time on the details that make an answer correct: ties, NULLs, duplicates, empty groups, and the boundaries of a date range.
Preparation is practice. Reading about a pattern helps, and writing it on fresh data, with a timer, helps more. The timed practice chapter of this course exists for that.
Schema design and internals
In a schema design question you receive requirements in words, for example "a clinic wants to book appointments for its doctors", and you produce tables. What gets weighed is whether the tables hold the facts the requirements need, whether the keys and constraints make wrong data impossible, and whether you can say which queries the design makes easy and which index it needs. The skills behind it are modelling, keys, normalisation and the first indexes.
An internals question appears inside a backend or system design round, and asks how the database behaves: why this query is slow, what happens when two users book the same seat, what a replica does with a write, or when you would shard. These are not queries to write. They are explanations to give, ideally backed by a number or by something you have seen run. The skills behind them are query plans, indexes, transactions and isolation, locking, replication, partitioning and the trade-offs between stores.
| Kind of question | You are given | You produce | It tests |
|---|---|---|---|
| Live SQL | Tables and a question | A query, checked on sample data | Pattern fluency and care with edge cases |
| Schema design | Requirements in words | Tables, keys, constraints, indexes | Modelling and the rules the database can enforce |
| Internals | A symptom or a scenario | An explanation with trade-offs | Knowing what the database does underneath |
You are givenTables and a question
Part 2 · What gets scored
Four things a good answer shows
An answer is more than the final query. A widely used public rubric, the Tech Interview Handbook's coding interview rubrics, scores four axes: communication, problem solving, technical competency and testing. It is a public rubric and not any company's policy, but the axes are useful because they describe what a listener sees.
This course turns the four axes into four criteria for a database answer. They are the same in every shape of question, and the mock chapter at the end uses exactly them.
| Criterion | What it asks | Closest rubric axis |
|---|---|---|
| Correct result | Does the query, schema or explanation give the right answer on the data? | Technical competency |
| Edge cases | Are NULLs, ties, duplicates, empty groups and range boundaries handled or named? | Testing |
| Clarity | Can a reader follow the steps, and did you say your reasoning aloud? | Communication |
| Trade-offs | Did you state an alternative, its cost, and the index or limit that matters? | Problem solving |
The mapping is approximate. A correct result is mostly technical competency, but also problem solving. Handling edge cases is testing, because a test is how you find them. Clarity is communication. Trade-offs belong to problem solving, which in the public rubric includes comparing approaches and discussing follow-ups. Treat the table as a way to remember what a listener is looking for, not as a precise conversion.
A query that passes the first criterion and fails the second
The easiest way to see the second criterion is a query that returns the right shape and is wrong on one row. The question: which staff member earns the most in each store? A natural first answer numbers the staff in each store by salary and keeps number 1. The data has a tie in store 1: Pooja and Nitin both earn 23,000 rupees.
CREATE TABLE staff ( staff_id int PRIMARY KEY, name text NOT NULL, store_id int NOT NULL, salary numeric(10,2) NOT NULL ); INSERT INTO staff (staff_id, name, store_id, salary) VALUES (1, 'Arjun', 1, 22000.00), (2, 'Pooja', 1, 23000.00), (3, 'Nitin', 1, 23000.00), (4, 'Kavita', 2, 52000.00), (5, 'Farah', 2, 20000.00);
SELECT store_id, name, salary FROM ( SELECT store_id, name, salary, row_number() OVER ( PARTITION BY store_id ORDER BY salary DESC ) AS rn FROM staff ) AS ranked WHERE rn = 1 ORDER BY store_id;
store_id | name | salary ---------+--------+--------- 1 | Pooja | 23000.00 2 | Kavita | 52000.00 (2 rows)
The result looks fine. It has one row per store and a plausible name. It is also wrong, because Nitin earns exactly as much as Pooja and has vanished. row_number() never gives two rows the same number, so it picked one of the tied rows. Which one it picks is not defined: this is one run, and another plan or another version may pick Nitin. The query passes the first look and fails the second criterion.
The fix, and saying it aloud
The fix is to let ties share a place. rank() gives tied rows the same number, so both staff in store 1 get place 1 and both are kept.
SELECT store_id, name, salary FROM ( SELECT store_id, name, salary, rank() OVER ( PARTITION BY store_id ORDER BY salary DESC ) AS rk FROM staff ) AS ranked WHERE rk = 1 ORDER BY store_id, name;
store_id | name | salary ---------+--------+--------- 1 | Nitin | 23000.00 1 | Pooja | 23000.00 2 | Kavita | 52000.00 (3 rows)
The PostgreSQL documentation describes rank as the rank of the current row with gaps, and dense_rank as the rank without gaps, and both give peers the same value. The three functions differ exactly on ties, so choosing one is a statement about what a tie should mean. When the question says "the top earner" and two people tie, the business usually wants both, and you can ask.
Talking shows the other criteria. Say "I assume ties should all appear, so I will use rank." That one sentence is clarity, a trade-off (the answer can return more than one row per store) and a handled edge case. Then add a final sort key, here the name, so that the printed order is the same on every run: an order that depends on a tie is undefined, and a stable output is easier to check.
The same habit applies to the other edge cases. NULLs: what does the query do with a missing value, and what should it do? Duplicates: can the same fact appear twice, and does a join multiply it? Empty groups: does a store with no staff appear, and should it? Boundaries: does "March" include the evening of 31 March? A good answer names the ones that matter and handles them, and a short sentence for each is enough.
Why can row_number() = 1 be wrong for "the top earner of each store"?
row_numbergives each row a different number, so with a tie it keeps one of the tied rows, chosen in an undefined way.rank() = 1keeps every row in the first place.
Which criterion does saying "I assume ties should all appear" help with?
Part 3 · A method for a SQL question
Five steps
A method keeps you moving when the clock runs and the question is new. The one used here has five steps: Clarify, Sketch, Build, Test, Tune. None of them is clever. The point is that every step produces something a listener can see, so a wrong turn is caught early and your reasoning is easy to follow.
- Clarify. State the grain, that is, what one output row stands for. Ask about the edge cases that matter: ties, NULLs, duplicates, empty groups, which statuses count, time zones and the exact boundaries of a period.
- Sketch. Draw the output table with two or three rows of made-up values, and name the tables and the joins that will produce them. If the sketch is wrong the question was misunderstood, and that is cheap to find out now.
- Build. Write the query in named steps, one idea per CTE, from the data towards the answer. A long single query hides mistakes, and small steps can be run and looked at one at a time.
- Test. Run it on a tiny dataset that contains the hard cases, and compare the result with the sketch. If a test fails, go back to Build.
- Tune. Name the index the query would use and what it would cost, or the alternative form you chose not to use, and why.
Here the method is applied to one question on the grocery delivery data: which customers ordered in March 2026 and did not order in April, and how much did each spend in March? The scene at the end of the lesson shows the five steps as they were followed, including a test that failed.
Clarify and sketch
Clarify. The grain is one row per customer. "Ordered" needs a decision: cancelled orders are not purchases, so only delivered orders count, in both months. Spend is quantity times unit price, summed over the March orders. A customer with no delivered order in March has nothing to report. April is the whole of April, from 1 April up to, but not including, 1 May.
Sketch. The output has two columns, the name and the March spend, and one row for each customer who qualifies. By hand, on the small data below, you expect: Meera, who bought once in March and never in April, and Ravi, whose only April order was cancelled. Asha spent 756 rupees in March but ordered again on the evening of 30 April, so she must not appear. Karthik ordered at midnight on 1 April, which is in April. Divya never ordered in March.
The tables are the ones from the grocery schema, cut down to the columns this question needs.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE customers ( customer_id int PRIMARY KEY, name text NOT NULL ); CREATE TABLE orders ( order_id int PRIMARY KEY, customer_id int NOT NULL REFERENCES customers (customer_id), placed_at timestamptz NOT NULL, status text NOT NULL ); CREATE TABLE order_items ( order_id int NOT NULL REFERENCES orders (order_id), product_id int NOT NULL, qty int NOT NULL, unit_price numeric(10,2) NOT NULL, PRIMARY KEY (order_id, product_id) );
INSERT INTO customers (customer_id, name) VALUES (1, 'Asha'), (2, 'Ravi'), (3, 'Meera'), (4, 'Karthik'), (5, 'Divya'); INSERT INTO orders (order_id, customer_id, placed_at, status) VALUES (1, 1, '2026-03-04 10:00', 'delivered'), (2, 2, '2026-03-10 18:30', 'delivered'), (3, 3, '2026-03-12 09:00', 'delivered'), (4, 3, '2026-03-20 20:00', 'cancelled'), (5, 4, '2026-03-30 11:00', 'delivered'), (6, 1, '2026-04-30 18:00', 'delivered'), (7, 2, '2026-05-02 12:00', 'delivered'), (8, 5, '2026-04-10 08:30', 'delivered'), (9, 4, '2026-04-01 00:00', 'delivered'), (10, 2, '2026-04-15 19:00', 'cancelled'); INSERT INTO order_items (order_id, product_id, qty, unit_price) VALUES (1, 1, 2, 58.00), (1, 4, 1, 640.00), (2, 2, 3, 40.00), (3, 3, 1, 95.00), (4, 4, 1, 640.00), (5, 7, 2, 70.00), (6, 1, 1, 58.00), (7, 2, 1, 40.00), (8, 1, 2, 58.00), (9, 3, 1, 95.00), (10, 2, 3, 40.00);
Build in steps
Build. The first step is the March spend per customer. It uses a half-open range for March, which has a closed start and an open end, so no instant of the month is missed or counted twice. Looking at it alone, the numbers match the sketch.
SELECT o.customer_id, sum(oi.qty * oi.unit_price) AS spend FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.order_id WHERE o.status = 'delivered' AND o.placed_at >= '2026-03-01' AND o.placed_at < '2026-04-01' GROUP BY o.customer_id ORDER BY o.customer_id;
customer_id | spend ------------+------- 1 | 756.00 2 | 120.00 3 | 95.00 4 | 140.00 (4 rows)
The second step removes the customers who ordered in April. This is an exclusion, so it is a NOT EXISTS against the delivered April orders of the same customer. For the first draft, April is written as BETWEEN '2026-04-01' AND '2026-04-30', because that is how the month looks on a calendar.
WITH march AS ( SELECT o.customer_id, sum(oi.qty * oi.unit_price) AS spend FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.order_id WHERE o.status = 'delivered' AND o.placed_at >= '2026-03-01' AND o.placed_at < '2026-04-01' GROUP BY o.customer_id ) SELECT c.name, m.spend FROM march AS m JOIN customers AS c ON c.customer_id = m.customer_id WHERE NOT EXISTS ( SELECT 1 FROM orders AS a WHERE a.customer_id = m.customer_id AND a.status = 'delivered' AND a.placed_at BETWEEN '2026-04-01' AND '2026-04-30' ) ORDER BY c.name;
name | spend ------+------- Asha | 756.00 Meera | 95.00 Ravi | 120.00 (3 rows)
Test, fix and tune
Test. The sketch said that Meera and Ravi qualify and Asha does not. The draft lists Asha. A BETWEEN with a date on the right means <= '2026-04-30', that is, midnight at the start of 30 April, so her order at 6 pm that day is outside the range. The filtering chapter covers the same boundary bug, and a test with an order late on the last day of the month is what catches it. The failing test sends the answer back to Build.
The fix is the half-open range that the March step already uses: from 1 April up to, not including, 1 May.
WITH march AS ( SELECT o.customer_id, sum(oi.qty * oi.unit_price) AS spend FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.order_id WHERE o.status = 'delivered' AND o.placed_at >= '2026-03-01' AND o.placed_at < '2026-04-01' GROUP BY o.customer_id ) SELECT c.name, m.spend FROM march AS m JOIN customers AS c ON c.customer_id = m.customer_id WHERE NOT EXISTS ( SELECT 1 FROM orders AS a WHERE a.customer_id = m.customer_id AND a.status = 'delivered' AND a.placed_at >= '2026-04-01' AND a.placed_at < '2026-05-01' ) ORDER BY c.name;
name | spend ------+------- Meera | 95.00 Ravi | 120.00 (2 rows)
Now the result matches the sketch. Karthik, whose order is exactly at midnight on 1 April, is correctly counted as an April customer, because the start of a half-open range is included.
Tune, and the whole path
Tune. On a table with many orders, the NOT EXISTS probe looks for rows of one customer in a time range, so an index on orders (customer_id, placed_at) serves it, and the March step would use a range scan on placed_at. An index slows writes a little and takes space, and a partial index on delivered orders would be smaller but would serve only this kind of query. Saying that much is enough, because the claim in this step is a design, not a measurement. The alternative form, a LEFT JOIN with an IS NULL test, gives the same rows.
Watch for the test step sending the answer back to Build
Read it as steps
The retention question: the April range written with BETWEEN fails the test and returns to Build.
The scene is the same work as a path through five states. The loop between Test and Build is not a sign of a weak answer. It is the method working, and a test you chose deliberately is the reason you found the bug before anybody else did.
Why does the draft list Asha although she ordered in April?
Part 4 · Design and internals questions, and a study plan
A method for a design question
A schema design question has the same need for steps, and the steps are about the data and not about a query. Start from the requirements, and say each rule out loud before you draw a table.
- Requirements. Underline the nouns, which become entities, the verbs, which become relationships, and the words like "must", "only" and "at most", which become constraints. Write down the questions the system has to answer, because those decide the indexes.
- Entities and keys. One table for each kind of thing, with a primary key. Decide what identifies a row in the real world, and add a unique constraint for it next to a surrogate key if you use one.
- Relationships. A foreign key for each one-to-many, and a junction table for each many-to-many. Say whether each side is required, which is a NOT NULL on the foreign key.
- Rules in the database. Check constraints for allowed values, unique constraints for "no two of", and an exclusion constraint where a rule is about overlapping ranges. A rule that the database enforces holds for every writer, including the one you did not know about.
- Access patterns and indexes. List the three or four main queries. For each, name the index it needs, in column order, and say what it costs on writes.
- Trade-offs. Name one place where you would denormalise on purpose, or one thing the design makes hard, and why you accept it.
The mock chapter has a worked design of this kind, for a clinic's appointments, with every constraint run against bad data.
A method for an internals question
An internals question asks you to explain a behaviour. The risk is an answer that is a list of terms. A four-part shape keeps it concrete.
- Name the mechanism in one sentence: what the database does, in plain words, such as "a unique index makes the second insert wait for the first to finish".
- Show what it prevents or causes: the failure it solves, or the symptom it explains. A booking that two users both win, a read that is a second old, a query that reads every page.
- State the cost: slower writes, memory, a wait, a retry that the application must handle.
- Give a number or a run. A plan with row counts, a measured time, the size of an index, or the outcome of a two-session test. Even a rough number, labelled as rough, is better than an adjective.
Take "why is this query slow?". The mechanism is the plan: the database chose to read every page, or to read the wrong number of rows because its statistics were out of date. What it causes is the time you are seeing. The cost of the fix, an index or fresh statistics, is slower writes or an extra maintenance step. The number is the plan before and after.
When you do not know, say what you would look at first. A plan with actual row counts, the table size, and the statistics views are all places to start. Naming the investigation is a stronger answer than a confident guess.
A four-week study plan
The plan below follows the order of this course. It divides the chapters into four weeks by reading time, about three to four hours each, which leaves room to run every example yourself and to repeat the timed practice. The minutes are the course's own estimates of reading time: running the code, and doing the practice rounds, take more than that, and you can reasonably plan for two or three times as long.
| Week | Chapters | Reading time |
|---|---|---|
| Week 1: design | plain files, the DBMS, data modelling, the ER model, the relational model, functional dependencies, normalisation | 180 min (3.0 h) |
| Week 2: SQL and the first patterns | SQL essentials, the patterns introduction, aggregation, filtering, comparison, sequencing and hierarchy | 188 min (3.1 h) |
| Week 3: reshaping, practice and internals | transformation, timed practice, indexes, query plans, transactions, isolation and MVCC | 198 min (3.3 h) |
| Week 4: concurrency, scale and the mock | locking, replication, partitioning and sharding, NoSQL models, DynamoDB keys, choosing a database, the mock | 244 min (4.1 h) |
Everything adds up to 810 minutes, about 13.5 hours of reading, apart from this chapter. If your goal is narrower, three shorter routes use the same chapters. For a SQL round only, read the SQL chapter, the six pattern chapters and the timed practice, and redo the practice rounds on a different day. For a design round, read the first seven chapters, then indexes and choosing a database. For internals and scale, read indexes, query plans, transactions, isolation, locking, replication, partitioning and sharding, and the NoSQL chapters, then the mock.
Each week ends the same way. Pick two problems or prompts you could not finish within the time, and redo them from a blank page two days later, saying your reasoning aloud. Score yourself with the four criteria from the scoring lesson. A low mark on edge cases means you should practise the checklist of ties, NULLs, duplicates, empty groups and boundaries. A low mark on trade-offs means you should finish every answer with one alternative and its cost.