Courses / Databases for Backend Interviews / Chapter 27
Module 12 · Mock interview · Chapter 27 of 27
Mock Interview: Five Timed Database Prompts with Model Answers
Builds on The Database Interview: Rounds, Scoring and a Study Plan, Data Modelling: From Requirements to Conceptual, Logical and Physical Models, Filtering Patterns: Existence, Exclusion, Aggregate Filters and Top-N per Group, Sequencing and Hierarchy Patterns: Streaks, Sessions and Recursive Trees, Indexes: B-Trees, Composite Keys, Covering and Partial Indexes, Query Plans: EXPLAIN, Statistics and Join Algorithms, Transactions: ACID, the Write-Ahead Log and Crash Recovery, Locks and Concurrency Control: Row Locks, Deadlocks and Optimistic Updates and Replication: Streaming Standbys, Lag, Failover and Logical Replication.
Part 1 · Prompt 1: top three per group (15 minutes)
The prompt
This chapter is a mock round. There are five prompts. For each one, set a timer for the time box, answer on paper or in an editor without looking, then read the model answer and score yourself on the four criteria from the interview chapter: correct result, edge cases, clarity and trade-offs, each marked 0, 1 or 2, so a prompt is worth 8. The time boxes are suggestions, and every output below is from a real run on PostgreSQL 18.6.
Prompt 1, 15 minutes. A grocery delivery service wants a report: for each city, its top three products by revenue from delivered orders. Revenue is quantity times unit price. If products tie, the report should not hide any of them. You may ask questions before you start.
The tables below are cut down to the columns the question needs. The data has a cancelled order with a large quantity that must not count, a tie for second place in Pune, and a city that sold only two products.
CREATE TABLE cities ( city_id int PRIMARY KEY, name text NOT NULL ); CREATE TABLE stores ( store_id int PRIMARY KEY, city_id int NOT NULL REFERENCES cities (city_id) ); CREATE TABLE products ( product_id int PRIMARY KEY, name text NOT NULL ); CREATE TABLE orders ( order_id int PRIMARY KEY, store_id int NOT NULL REFERENCES stores (store_id), status text NOT NULL ); CREATE TABLE order_items ( order_id int NOT NULL REFERENCES orders (order_id), product_id int NOT NULL REFERENCES products (product_id), qty int NOT NULL, unit_price numeric(10,2) NOT NULL, PRIMARY KEY (order_id, product_id) );
INSERT INTO cities (city_id, name) VALUES (1, 'Pune'), (2, 'Nagpur'); INSERT INTO stores (store_id, city_id) VALUES (1, 1), (2, 1), (3, 2); INSERT INTO products (product_id, name) VALUES (1, 'Toned milk 1 L'), (2, 'Curd 500 g'), (3, 'Paneer 200 g'), (4, 'Basmati rice 5 kg'), (5, 'Salted peanuts 200 g'), (6, 'Wheat flour 5 kg'); INSERT INTO orders (order_id, store_id, status) VALUES (1, 1, 'delivered'), (2, 2, 'delivered'), (3, 1, 'delivered'), (4, 2, 'cancelled'), (5, 3, 'delivered'); INSERT INTO order_items (order_id, product_id, qty, unit_price) VALUES (1, 4, 1, 640.00), (1, 6, 2, 245.00), (2, 4, 1, 640.00), (2, 2, 7, 40.00), (3, 5, 7, 70.00), (3, 3, 2, 95.00), (3, 1, 2, 58.00), (4, 3, 20, 95.00), (5, 1, 10, 58.00), (5, 4, 1, 640.00);
Model answer
Clarify. One output row per city and product, ranked within the city. Only delivered orders count. "Top three with ties" is ambiguous, so state a choice: a product is in the top three if fewer than three products earned more than it, which is what rank() gives. With a tie inside the top three, both tied products appear. If the other reading is wanted, dense_rank() is a one-word change.
Build. Step one totals the revenue of each product in each city. The city is reached through the store of the order. Looking at that step by itself first is the quickest check that the joins and the status filter are right.
SELECT c.name AS city, p.name AS product, sum(oi.qty * oi.unit_price) AS revenue FROM order_items AS oi JOIN orders AS o ON o.order_id = oi.order_id JOIN stores AS s ON s.store_id = o.store_id JOIN cities AS c ON c.city_id = s.city_id JOIN products AS p ON p.product_id = oi.product_id WHERE o.status = 'delivered' GROUP BY c.name, p.name ORDER BY c.name, revenue DESC, p.name;
city | product | revenue -------+----------------------+-------- Nagpur | Basmati rice 5 kg | 640.00 Nagpur | Toned milk 1 L | 580.00 Pune | Basmati rice 5 kg | 1280.00 Pune | Salted peanuts 200 g | 490.00 Pune | Wheat flour 5 kg | 490.00 Pune | Curd 500 g | 280.00 Pune | Paneer 200 g | 190.00 Pune | Toned milk 1 L | 116.00 (8 rows)
Step two ranks the products inside each city and keeps places 1 to 3 in an outer query, since a window function cannot be filtered in the query that computes it.
WITH revenue AS ( SELECT c.name AS city, p.name AS product, sum(oi.qty * oi.unit_price) AS revenue FROM order_items AS oi JOIN orders AS o ON o.order_id = oi.order_id JOIN stores AS s ON s.store_id = o.store_id JOIN cities AS c ON c.city_id = s.city_id JOIN products AS p ON p.product_id = oi.product_id WHERE o.status = 'delivered' GROUP BY c.name, p.name ), ranked AS ( SELECT city, product, revenue, rank() OVER (PARTITION BY city ORDER BY revenue DESC) AS place FROM revenue ) SELECT city, product, revenue, place FROM ranked WHERE place <= 3 ORDER BY city, place, product;
city | product | revenue | place -------+----------------------+---------+------ Nagpur | Basmati rice 5 kg | 640.00 | 1 Nagpur | Toned milk 1 L | 580.00 | 2 Pune | Basmati rice 5 kg | 1280.00 | 1 Pune | Salted peanuts 200 g | 490.00 | 2 Pune | Wheat flour 5 kg | 490.00 | 2 (5 rows)
Checks and rubric
Test. Pune has two products tied at 490 rupees for second place, and both are in the result. Curd, next at 280, is in place 4 and is left out, because rank skips place 3 after a tie. The cancelled order of 20 packs of paneer, worth 1,900 rupees, is not counted, which is why paneer is only at 190 and out of the top three. Nagpur sold two products and shows two rows, not three, so the query does not invent a third. Trade-offs. With dense_rank the same data gives a different number of rows, shown below. The choice is a business decision, and saying so is the trade-off.
WITH revenue AS ( SELECT s.city_id, oi.product_id, sum(oi.qty * oi.unit_price) AS revenue FROM order_items AS oi JOIN orders AS o ON o.order_id = oi.order_id JOIN stores AS s ON s.store_id = o.store_id WHERE o.status = 'delivered' GROUP BY s.city_id, oi.product_id ), ranked AS ( SELECT city_id, product_id, dense_rank() OVER ( PARTITION BY city_id ORDER BY revenue DESC ) AS place FROM revenue ) SELECT city_id, count(*) AS rows_kept FROM ranked WHERE place <= 3 GROUP BY city_id ORDER BY city_id;
city_id | rows_kept --------+---------- 1 | 4 2 | 2 (2 rows)
Pune keeps four rows under dense_rank and three under rank. After the tie at second place, dense_rank gives curd place 3, so curd stays, while rank gives it place 4. Both readings are defensible, and the reader of the report decides which one is wanted.
Common slips. Four mistakes are easy to make on this prompt. Counting orders instead of summing quantity times price gives a ranking by popularity, not by revenue. Forgetting the status filter lets the cancelled order push paneer to the top of Pune. Using row_number silently drops one of two tied products, and the choice of which one is undefined. And grouping by the name of the city alone, when two cities share a name in different states, merges them, which is why a careful answer asks whether the city id is the better key. Saying which of these you checked, aloud, earns the clarity mark even when the query is short.
| Criterion | Full marks (2) needs |
|---|---|
| Correct result |
Part 2 · Prompt 2: streaks and sessions (20 minutes)
The prompt
Prompt 2, 20 minutes. Two questions on the same data. First: for each customer, what is the longest run of consecutive days on which they received a delivered order? Second: the app records events, and a new session starts when a customer has been silent for more than 30 minutes. For each session, show when it started, how many events it had and whether it reached the checkout.
The data has a customer who ordered twice on the same day, a cancelled order that must not extend a streak, a customer whose events include a gap of more than 30 minutes, and a second customer with a gap of exactly 20 minutes.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE orders ( order_id int PRIMARY KEY, customer_id int NOT NULL, placed_at timestamptz NOT NULL, status text NOT NULL ); CREATE TABLE app_events ( customer_id int NOT NULL, event_at timestamptz NOT NULL, event_type text NOT NULL ); INSERT INTO orders (order_id, customer_id, placed_at, status) VALUES (1, 1, '2026-04-01 09:00', 'delivered'), (2, 1, '2026-04-02 09:00', 'delivered'), (3, 1, '2026-04-02 21:00', 'delivered'), (4, 1, '2026-04-03 09:00', 'delivered'), (5, 1, '2026-04-05 09:00', 'delivered'), (6, 1, '2026-04-06 09:00', 'cancelled'), (7, 2, '2026-04-04 10:00', 'delivered'), (8, 2, '2026-04-05 10:00', 'delivered'); INSERT INTO app_events (customer_id, event_at, event_type) VALUES (1, '2026-04-05 08:50', 'open'), (1, '2026-04-05 08:58', 'search'), (1, '2026-04-05 09:30', 'checkout'), (1, '2026-04-05 12:00', 'open'), (2, '2026-04-05 10:00', 'open'), (2, '2026-04-05 10:20', 'search');
Model answer: streaks
Clarify. The grain of the first answer is one row per customer. A day counts once however many orders were placed on it, and only delivered orders count. If two streaks are equally long, the earlier one is shown.
Build. Reduce the orders to distinct customer and day pairs. Number the days of each customer. The day minus its number is constant inside a streak. Group by that value to get each streak, then keep the longest one for each customer. The step that removes duplicate days is the one a hasty answer forgets.
WITH days AS ( SELECT DISTINCT customer_id, placed_at::date AS day FROM orders WHERE status = 'delivered' ), grouped AS ( SELECT customer_id, day, day - (row_number() OVER ( PARTITION BY customer_id ORDER BY day ))::int AS grp FROM days ), islands AS ( SELECT customer_id, min(day) AS first_day, max(day) AS last_day, count(*) AS streak_days FROM grouped GROUP BY customer_id, grp ), ranked AS ( SELECT customer_id, first_day, last_day, streak_days, row_number() OVER ( PARTITION BY customer_id ORDER BY streak_days DESC, first_day ) AS rk FROM islands ) SELECT customer_id, first_day::text AS first_day, last_day::text AS last_day, streak_days FROM ranked WHERE rk = 1 ORDER BY customer_id;
customer_id | first_day | last_day | streak_days ------------+------------+------------+------------ 1 | 2026-04-01 | 2026-04-03 | 3 2 | 2026-04-04 | 2026-04-05 | 2 (2 rows)
Customer 1 has orders on 1, 2 and 3 April, and the two orders on 2 April count as one day. The next order is on 5 April, which breaks the streak, and the cancelled order on 6 April does not extend it. The longest streak is three days. Customer 2 has two days in a row.
Model answer: sessions, and the rubric
Build. For the sessions, take the gap to the previous event of the same customer with lag. Mark an event as a session start when there is no previous event or the gap is more than 30 minutes. A running sum of the marks gives each event its session number, and an ordinary GROUP BY summarises the sessions.
WITH flagged AS ( SELECT customer_id, event_at, event_type, CASE WHEN lag(event_at) OVER w IS NULL OR event_at - lag(event_at) OVER w > interval '30 minutes' THEN 1 ELSE 0 END AS new_session FROM app_events WINDOW w AS (PARTITION BY customer_id ORDER BY event_at) ), numbered AS ( SELECT customer_id, event_at, event_type, sum(new_session) OVER ( PARTITION BY customer_id ORDER BY event_at ) AS session_no FROM flagged ) SELECT customer_id AS customer, session_no AS session, min(event_at)::time::text AS started, count(*) AS events, bool_or(event_type = 'checkout') AS checkout FROM numbered GROUP BY customer_id, session_no ORDER BY customer_id, session_no;
customer | session | started | events | checkout ---------+---------+----------+--------+--------- 1 | 1 | 08:50:00 | 2 | false 1 | 2 | 09:30:00 | 1 | true 1 | 3 | 12:00:00 | 1 | false 2 | 1 | 10:00:00 | 2 | false (4 rows)
Customer 1 has three sessions. The first opens at 08:50 and holds two events. The checkout at 09:30 comes 32 minutes after the event at 08:58, which is more than 30, so it starts the second session. The event at noon starts the third. Customer 2 has a gap of exactly 20 minutes and stays in one session of two events.
Trade-offs. Say that the 30 minutes is a parameter, that "more than" and "at least" differ at exactly 30 minutes, and that on a large events table you would want an index on (customer_id, event_at) so that the window can read each customer's events in order without sorting everything.
Alternatives, and the rubric
An alternative to name. The streak can also be found without the label trick. A recursive query can walk from each day to the next day with an order, and a self-join can compare each day with the previous one. Both are longer and slower on a big table than one window function, which is why the label method is the usual answer. Mentioning an alternative and the reason you did not choose it is the trade-offs mark, and it takes one sentence.
Check it on a second customer. The second customer is a short test of the method itself. Two days in a row give a streak of 2, and nothing else interferes. If your query gives a different number for them, the problem is in the grouping step and not in the data.
| Criterion | Full marks (2) needs |
|---|---|
| Correct result | Distinct days, a constant label inside a streak, the longest streak per customer; sessions numbered with lag and a running sum. |
| Edge cases | Two orders on one day, the cancelled order excluded, the first event of each customer as a session start, the exact threshold. |
| Clarity | Each step is a named CTE, and the idea of the label is said aloud. |
| Trade-offs | The threshold as a parameter, > against >=, and an index on customer and time. |
Why does customer 1 have a three-day streak and not four?
- The orders are on 1, 2, 3 and 5 April. The 6 April order was cancelled, and 5 April is not next to 3 April.
- The two orders on 2 April count as one day.
Which event starts customer 1's second session, and why?
- The checkout at 09:30, because it comes 32 minutes after the previous event at 08:58, which is more than 30 minutes.
Part 3 · Prompt 3: schema design (20 minutes)
The prompt
Prompt 3, 20 minutes. A small clinic in Pune wants to book appointments. Doctors have a name and a speciality. Patients have a name and a phone number. A patient books an appointment with a doctor for a time range. A doctor cannot have two appointments that overlap. An appointment can be cancelled, and the clinic wants to keep cancelled appointments for its records, and a cancelled slot can be booked again. Patients ask to see their own appointments, newest first. Design the tables.
Say the entities first, then the keys, then the rules the database should enforce, then the two queries that matter and the index each needs. A diagram of the tables is a good way to start.
Model answer: tables and rules
Requirements to tables. The nouns are doctor, patient and appointment. The appointment is the relationship between a doctor and a patient at a time, and it has attributes of its own, so it is a table with two foreign keys, a start, an end and a status. Doctors and patients are small tables with a surrogate key.
Rules in the database. The status can only be booked, cancelled or completed, which is a CHECK. The end must be after the start, another CHECK. The rule "no two overlapping appointments for a doctor" is the interesting one. A UNIQUE constraint on doctor and start time catches two appointments at the same instant, but not a 10:00 to 10:30 appointment beside a 10:15 to 10:45 one. An exclusion constraint says it directly: no two rows may have the same doctor and overlapping time ranges. It needs the btree_gist extension so that equality on the doctor can use the same index as the range overlap. The constraint is limited to rows whose status is not cancelled, so that a cancelled slot can be booked again.
SET TIME ZONE 'Asia/Kolkata'; CREATE EXTENSION btree_gist; CREATE TABLE doctors ( doctor_id int PRIMARY KEY, name text NOT NULL, speciality text NOT NULL ); CREATE TABLE patients ( patient_id int PRIMARY KEY, name text NOT NULL, phone text NOT NULL ); CREATE TABLE appointments ( appointment_id int PRIMARY KEY, doctor_id int NOT NULL REFERENCES doctors (doctor_id), patient_id int NOT NULL REFERENCES patients (patient_id), starts_at timestamptz NOT NULL, ends_at timestamptz NOT NULL, status text NOT NULL DEFAULT 'booked' CHECK (status IN ('booked', 'cancelled', 'completed')), CHECK (ends_at > starts_at), EXCLUDE USING gist ( doctor_id WITH =, tstzrange(starts_at, ends_at) WITH && ) WHERE (status <> 'cancelled') ); CREATE INDEX appointments_patient_idx ON appointments (patient_id, starts_at DESC);
Running it against bad data
A design is only a claim until it is run against data that breaks it. Two doctors and two patients are inserted, then the first appointment.
INSERT INTO doctors (doctor_id, name, speciality) VALUES (1, 'Dr Iyer', 'general'), (2, 'Dr Bose', 'paediatrics'); INSERT INTO patients (patient_id, name, phone) VALUES (1, 'Asha', '+91 04412-345678'), (2, 'Ravi', '+91 04412-345600');
INSERT INTO appointments (appointment_id, doctor_id, patient_id, starts_at, ends_at) VALUES (1, 1, 1, '2026-04-06 10:00', '2026-04-06 10:30') RETURNING appointment_id, status;
appointment_id | status ---------------+------- 1 | booked (1 row)
A second appointment for the same doctor at 10:15 overlaps the first, and the database refuses it with the SQLSTATE for an exclusion violation, 23P01.
INSERT INTO appointments (appointment_id, doctor_id, patient_id, starts_at, ends_at) VALUES (2, 1, 2, '2026-04-06 10:15', '2026-04-06 10:45');
ERROR 23P01: conflicting key value violates exclusion constraint
"appointments_doctor_id_tstzrange_excl"An appointment that starts exactly when the first one ends is accepted, because time ranges in PostgreSQL include their start and exclude their end by default. The same time for another doctor is also accepted.
INSERT INTO appointments (appointment_id, doctor_id, patient_id, starts_at, ends_at) VALUES (3, 1, 2, '2026-04-06 10:30', '2026-04-06 11:00') RETURNING appointment_id, status;
appointment_id | status ---------------+------- 3 | booked (1 row)
INSERT INTO appointments (appointment_id, doctor_id, patient_id, starts_at, ends_at) VALUES (4, 2, 2, '2026-04-06 10:15', '2026-04-06 10:45') RETURNING appointment_id, status;
appointment_id | status ---------------+------- 4 | booked (1 row)
Cancelling, other checks and the indexes
Cancelling the first appointment frees the slot, because cancelled rows are outside the constraint, and the same time can then be booked again. The cancelled row stays for the records.
UPDATE appointments SET status = 'cancelled' WHERE appointment_id = 1 RETURNING appointment_id, status;
appointment_id | status ---------------+---------- 1 | cancelled (1 row)
INSERT INTO appointments (appointment_id, doctor_id, patient_id, starts_at, ends_at) VALUES (5, 1, 2, '2026-04-06 10:00', '2026-04-06 10:30') RETURNING appointment_id, status;
appointment_id | status ---------------+------- 5 | booked (1 row)
The other rules work as well. An end before the start fails the check constraint with 23514, and a patient who does not exist fails the foreign key with 23503.
INSERT INTO appointments (appointment_id, doctor_id, patient_id, starts_at, ends_at) VALUES (6, 2, 1, '2026-04-07 10:00', '2026-04-07 09:00');
ERROR 23514: new row for relation "appointments" violates check constraint "appointments_check"
INSERT INTO appointments (appointment_id, doctor_id, patient_id, starts_at, ends_at) VALUES (7, 2, 99, '2026-04-07 10:00', '2026-04-07 10:30');
ERROR 23503: insert or update on table "appointments" violates foreign key constraint "appointments_patient_id_fkey"
Indexes. The exclusion constraint created its own index on the doctor and the time range, and it may also help the question "what is this doctor's day?", which is worth checking with EXPLAIN. The patient's list needs a second index, on (patient_id, starts_at DESC), so that the newest appointments of one patient are read in order. The primary keys have their indexes too.
SELECT indexname FROM pg_indexes WHERE tablename = 'appointments' ORDER BY indexname;
indexname
-------------------------------------
appointments_doctor_id_tstzrange_excl
appointments_patient_idx
appointments_pkey
(3 rows)Trade-offs. Keeping cancelled rows costs space and makes the constraint partial, and the alternative is a separate history table. A fixed slot length would allow the simpler UNIQUE (doctor_id, starts_at) and no extension. Storing the doctor's speciality as text is easy to start with, and a separate table would be better if the clinic needs a managed list.
Part 4 · Prompt 4: a slow query (15 minutes)
The prompt
Prompt 4, 15 minutes. A delivery table has 2 lakh rows. A page that lists the deliveries of one pincode in one city got slow as the table grew. Here is the query and its plan. Say what is wrong, what you would change, and how you would check that the change worked. The table is deliveries (delivery_id, city, pincode, rider_id, delivered_at), with a primary key and no other index, and it has 20 cities of 5 pincodes each, 2,000 rows per pincode.
SELECT delivery_id, rider_id FROM deliveries WHERE city = 'city01' AND pincode = '401000';
The plans below come from a real server, PostgreSQL 18.6, started for this lesson, with EXPLAIN (ANALYZE, BUFFERS, TIMING OFF). The lines about planning buffers are left out. Times are in milliseconds on this machine, and they vary from run to run. The estimates vary a little too, for the reason the indexes chapter gave, because ANALYZE reads a sample of the table: a second run of this lesson, on a fresh server, estimated 102, 107 and 1,953 rows where the run shown estimates 107, 92 and 1,933.
Gather (cost=1000.00..4246.41 rows=107 width=8) (actual rows=2000.00 loops=1) Workers Planned: 1 Workers Launched: 1 Buffers: shared hit=1471 -> Parallel Seq Scan on deliveries (cost=0.00..3235.71 rows=63 width=8) (actual rows=1000.00 loops=2) Filter: ((city = 'city01'::text) AND (pincode = '401000'::text)) Rows Removed by Filter: 99000 Buffers: shared hit=1471 Planning Time: 0.093 ms Execution Time: 30.040 ms
Diagnosis
Read the plan. The node at the bottom is a Parallel Seq Scan. The database reads all the pages of the table, 1,471 of them, and throws away about 99,000 rows in each of two workers, to return 2,000 rows. That is the cost that grows with the table. The 30 ms is small today, and it grows in proportion to the table.
Read the estimate. The scan is expected to return 63 rows per worker and the gather node 107, but the actual numbers are 1,000 per worker and 2,000 in total. The estimate is out by a factor of about 19. The reason is that the planner treats the city and the pincode as independent. A pincode belongs to exactly one city, so once the pincode is known the city adds no selectivity, but the planner multiplies the two fractions, one in 20 and one in 100, and expects one row in 2,000 where the real figure is one in 100.
A misestimate like this one does no harm to this plan, but it grows into a wrong choice when the query is a join, since join order and method depend on row counts. So there are two things to fix: the missing index and the bad statistics.
The fix, and checking it
The index. The query filters on the pincode, so an index on the pincode lets the database find the 2,000 rows without reading the table. The first run after creating it is shown, with the statistics refreshed by ANALYZE.
CREATE INDEX deliveries_pincode_idx ON deliveries (pincode); ANALYZE deliveries;
Bitmap Heap Scan on deliveries (cost=22.57..1600.72 rows=92 width=8) (actual rows=2000.00 loops=1) Recheck Cond: (pincode = '401000'::text) Filter: (city = 'city01'::text) Heap Blocks: exact=1471 Buffers: shared hit=1471 read=3 -> Bitmap Index Scan on deliveries_pincode_idx (cost=0.00..22.55 rows=1900 width=0) (actual rows=2000.00 loops=1) Index Cond: (pincode = '401000'::text) Index Searches: 1 Buffers: shared read=3 Planning Time: 0.363 ms Execution Time: 2.913 ms
The plan changed from a sequential scan to a bitmap index scan, and the time dropped from about 30 ms to about 3 ms on this machine. In the second run it went from 43 ms to 1.6 ms, so read the size of the change, tens of milliseconds down to a few, and not the digits. The heap still shows 1,471 blocks, because the 2,000 rows are spread over every page of this table. If the rows of one pincode were stored together, fewer pages would be touched. The estimate is still wrong, 92 rows against 2,000.
The statistics. Extended statistics tell the planner that the two columns depend on each other.
CREATE STATISTICS deliveries_city_pin (dependencies) ON city, pincode FROM deliveries; ANALYZE deliveries;
Bitmap Heap Scan on deliveries (cost=23.28..1601.95 rows=1933 width=8) (actual rows=2000.00 loops=1) Recheck Cond: (pincode = '401000'::text) Filter: (city = 'city01'::text) Heap Blocks: exact=1471 Buffers: shared hit=1474 -> Bitmap Index Scan on deliveries_pincode_idx (cost=0.00..22.79 rows=1933 width=0) (actual rows=2000.00 loops=1) Index Cond: (pincode = '401000'::text) Index Searches: 1 Buffers: shared hit=3 Planning Time: 0.147 ms Execution Time: 1.256 ms
Result and rubric
The estimate is now 1,933 rows against 2,000 actual, and the plan itself did not change. The last run took 1.3 ms against 2.9 ms before, but its buffers are all hits, while the run before it counted three reads, which are buffers that were not yet in the server's own cache (they may have come from the operating system's cache and not from the disk). Repeating the same plan in the second run gave 1.6, 1.7 and 1.9 ms with identical buffers, and the plan after the statistics took 2.0 ms there. A difference of a millisecond or so between runs of the same plan is noise, so do not credit the statistics with a speed-up. What they changed is the estimate, and a better estimate matters when this query becomes part of a join.
How to check the change in a real system. Run the same query with EXPLAIN (ANALYZE, BUFFERS) before and after, on data of realistic size. Look at the scan type, the rows removed by the filter, the buffers, and the gap between estimated and actual rows. The index has a cost: every insert into the table now updates a second index, so check the write path as well. And drop an index that no query uses.
Trade-offs. An index on (pincode, city) or on (city, pincode) would also work, and the pincode alone is smaller. Since the pincode determines the city, the best fix to the query itself is to drop the redundant city condition. The data model, not the planner, is what knows the dependency.
| Criterion | Full marks (2) needs |
|---|---|
| Correct result | Finds the sequential scan and the filter that discards most rows, and proposes an index on the pincode. |
| Edge cases | Notices the estimate against actual rows, links it to the two columns being treated as independent, and proposes statistics. |
| Clarity | Reads the plan from the bottom up, naming the node, the rows removed and the buffers. |
| Trade-offs | Write cost of the index, an alternative column order, dropping the redundant condition, and checking before and after on realistic data. |
Part 5 · Prompt 5: double booking and stale reads (15 minutes)
The prompt
Prompt 5, 15 minutes. A bus booking service lets riders pick seats. Two riders tap the same seat at the same moment, and both get a confirmation. The team also notices that a rider who has just booked sometimes opens "my bookings" and does not see the booking, because that page reads from a replica. Explain both problems and fix them.
Both are concurrency problems, and both are easier to explain with a run. The first is shown with two real sessions on a PostgreSQL 18.6 server, using the two-session harness from the transactions chapter. Statements of the two sessions are shown side by side in the order they ran, reformatted as a table.
| Step | Session A | Session B |
|---|---|---|
| 1 | BEGIN | BEGIN |
| 2 | count seat 12 on trip 7: 0 | count seat 12 on trip 7: 0 |
| 3 | INSERT (7, 12, Asha) | |
| 4 | INSERT (7, 12, Ravi): accepted | |
| 5 | COMMIT | COMMIT |
bookings after both commits: trip_id | seat_no | rider --------+---------+------ 7 | 12 | Asha 7 | 12 | Ravi
Why the check does not protect you
Both sessions asked "is seat 12 taken?" and both heard "no", because neither had committed. Each then inserted its booking. The application did a check then act: read a fact, decide, write. Between the read and the write, another transaction changed the fact. Nothing in the table says that a seat can be booked once, so the database accepted both rows. A lock inside the application would not help either, since a second application server has its own lock.
The fix: put the rule in the database. A UNIQUE (trip_id, seat_no) constraint makes the second booking impossible. When B tried the insert, it waited, since the first insert had not committed and the database could not yet know whether the key would be taken. After A committed, B's insert failed.
| Step | Session A | Session B |
|---|---|---|
| 1 | BEGIN | BEGIN |
| 2 | INSERT (7, 12, Asha) | |
| 3 | INSERT (7, 12, Ravi): still waiting after 500 ms | |
| 4 | COMMIT | |
| 5 | ERROR 23505: duplicate key value violates unique constraint "one_rider_per_seat" | |
| 6 | ROLLBACK |
bookings after the run: trip_id | seat_no | rider --------+---------+------ 7 | 12 | Asha
Alternatives, and the stale read
The application has to handle error 23505 and tell Ravi that the seat is gone. A different way is INSERT ... ON CONFLICT (trip_id, seat_no) DO NOTHING RETURNING booking_id. When the seat is taken, no row is returned, so the application sees an empty result and not an exception. When the seat is already taken it returns no rows. Another option is a row lock: keep one row per seat and use SELECT ... FOR UPDATE before the booking, so the second rider waits on the lock. That suits a seat table that already exists, and the unique constraint suits a bookings table that records each booking. All three give the same guarantee, one rider for each seat, and the constraint is the one that survives bugs elsewhere.
The stale read. A replica applies the changes of the primary after the primary commits them. The PostgreSQL documentation says that streaming replication is asynchronous by default, so there is a small delay between a commit on the primary and the change becoming visible on the standby, typically under one second assuming the standby is powerful enough to keep up with the load. A rider who books and immediately opens a page that reads from the replica can fall inside that delay and see an older state.
The fixes are about routing. For a short time after a rider writes, send that rider's reads to the primary. Or send "my bookings" to the primary always and keep the replicas for pages where a stale read does no harm, like browsing routes. The database can also wait: with synchronous_commit = remote_apply and a synchronous standby configured, the documentation says a commit waits until the synchronous standbys report that they have replayed it, so it is visible to queries there, at the price of slower commits and a dependency on the standby. This prompt does not run a replica, so these are statements from the documentation and not output.
Rubric and the whole mock
| Criterion | Full marks (2) needs |
|---|---|
| Correct result | Explains check-then-act, and enforces one rider per seat with a constraint, an ON CONFLICT clause or a row lock. |
| Edge cases | The second rider waits and then fails with 23505, which the application must handle; the row is rolled back; the stale read happens only after a very recent write. |
| Clarity | The interleaving of the two sessions is described step by step, in order. |
| Trade-offs | Unique constraint against row lock; routing reads to the primary against remote_apply and its cost; replicas kept for pages where stale reads are harmless. |
Scoring the mock. Score each of the five prompts out of 8 with the criteria above and write the five totals down. The totals matter less than the pattern across them. A prompt that scored 2 on correctness and 0 on edge cases shows a habit, and the habit is what to practise: the checklist of ties, NULLs, duplicates, empty groups and boundaries. Redo the prompts you scored lowest on after a few days, from a blank page, and compare the answer with the model answer line by line.
Why did both riders see the seat as free?
- Each session read the count before the other had committed, so both saw 0, and neither wrote anything that stopped the other.
- Check-then-act is not safe without a constraint or a lock.
Why did the second insert wait in the run with the unique constraint?
- The first insert had not committed, so the database could not decide whether the key was taken, and it made the second wait for the first transaction to finish.
- After the commit, the second insert failed with 23505.
All chapters · Previous: Choosing a Database: Matching Workloads to Relational and NoSQL Stores