Courses / Databases for Backend Interviews / Chapter 16
Module 7 · SQL patterns: comparing, sequencing and reshaping · Chapter 16 of 27
Timed SQL Practice: Three Rounds Across Every Pattern
Builds on The Relational Model: Relations, Keys, Integrity and Relational Algebra, Aggregation Patterns: Tally Counts, Group Buckets and Rolling Totals, Filtering Patterns: Existence, Exclusion, Aggregate Filters and Top-N per Group, Comparison Patterns: Row Against Group, Neighbour and Earlier Period, Sequencing and Hierarchy Patterns: Streaks, Sessions and Recursive Trees and Transformation Patterns: Pivoting, Unpivoting, Text and JSON. Next up: Indexes: B-Trees, Composite Keys, Covering and Partial Indexes.
Part 1 · Round one: aggregation and filtering (25 minutes)
How to use these rounds
Each round holds three problems on the patterns of the earlier chapters. Read the brief, set a timer, write your own query before you open the solution, and run it on the data given. The times are suggestions: about 8 minutes a problem in round one, and a little more in the later rounds. Stopping at the time and reading the solution teaches more than an hour spent stuck.
Every problem creates its own small tables, with at most 12 rows each, so you can paste a problem into any PostgreSQL 18 session and get the results shown. Only the columns the problem needs are created, with the names from the grocery delivery schema. The results below were produced by running exactly the code on the page. Results are printed with the helper from the SQL chapter.
A habit that pays in a timed setting: before you write anything, say the grain of the answer, which is what one output row stands for. Then write the query in steps, check it against the small data by eye, and look at ties, NULLs and empty groups before you declare it done.
Problem 1: weekly revenue with no gaps
Brief. Show the revenue of delivered orders for each of the four weeks starting Monday 2 March 2026, with a zero for a week that had no delivered orders. Revenue is quantity times unit price.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE orders ( order_id int PRIMARY KEY, 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 orders (order_id, placed_at, status) VALUES (1, '2026-03-03 10:00', 'delivered'), (2, '2026-03-05 19:30', 'delivered'), (3, '2026-03-10 09:00', 'cancelled'), (4, '2026-03-18 12:15', 'delivered'), (5, '2026-03-19 20:40', 'delivered'), (6, '2026-03-25 08:30', '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, 1, 5, 58.00), (4, 3, 2, 95.00), (5, 1, 4, 58.00), (5, 2, 1, 40.00), (6, 4, 1, 640.00);
Approach. The output has one row per week, and two of the weeks have no delivered orders, so the weeks cannot come from the orders alone. Generate the four Mondays, sum the delivered revenue per week in a second CTE, and left join the second to the first. coalesce turns the missing sum into zero.
WITH weeks AS ( SELECT d::date AS week_start FROM generate_series(date '2026-03-02', date '2026-03-23', interval '7 days') AS g (d) ), revenue AS ( SELECT date_trunc('week', o.placed_at)::date AS week_start, sum(oi.qty * oi.unit_price) AS revenue FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.order_id WHERE o.status = 'delivered' GROUP BY 1 ) SELECT w.week_start::text AS week_start, coalesce(r.revenue, 0) AS revenue FROM weeks AS w LEFT JOIN revenue AS r ON r.week_start = w.week_start ORDER BY w.week_start;
week_start | revenue -----------+-------- 2026-03-02 | 876.00 2026-03-09 | 0 2026-03-16 | 462.00 2026-03-23 | 0 (4 rows)
Why it works. date_trunc('week', ...) rounds a timestamp down to its Monday, so the revenue CTE and the generated weeks use the same key. The cancelled orders are removed in the WHERE, before the sum, which is why the second and fourth weeks have no rows in the revenue CTE and show up only through the left join. Had the weeks been joined straight to the orders, a WHERE status = 'delivered' after that join would have thrown away the weeks with no orders and turned the left join into an inner join.
Problem 2: steady customers
Brief. List the customers who have placed at least two orders and have never had an order cancelled, with their order counts.
CREATE TABLE orders ( order_id int PRIMARY KEY, customer_id int NOT NULL, status text NOT NULL ); INSERT INTO orders (order_id, customer_id, status) VALUES (1, 1, 'delivered'), (2, 1, 'delivered'), (3, 1, 'placed'), (4, 2, 'delivered'), (5, 2, 'cancelled'), (6, 2, 'delivered'), (7, 3, 'delivered'), (8, 4, 'delivered'), (9, 4, 'delivered');
Approach. The condition is about the whole group of a customer, so it goes in HAVING. "At least two orders" is count(*) >= 2. "Never cancelled" is a count of the cancelled orders that must equal zero, which count(*) FILTER (WHERE ...) gives directly and returns 0, not NULL, for a customer without any.
SELECT customer_id, count(*) AS orders FROM orders GROUP BY customer_id HAVING count(*) >= 2 AND count(*) FILTER (WHERE status = 'cancelled') = 0 ORDER BY customer_id;
customer_id | orders ------------+------- 1 | 3 4 | 2 (2 rows)
Why it works. Customer 1 has a placed order and two delivered ones, and only cancelled orders disqualify. Customer 2 has two delivered orders, but one cancelled order sinks them. Customer 3 has a single order, and customer 4 qualifies. A WHERE status <> 'cancelled' would have been wrong in a subtle way, since it removes the cancelled rows and lets customer 2 pass with two orders. A condition about a group needs an aggregate, not a row filter.
Problem 3: the two best sellers per category
Brief. For each category, list the products with the highest and the second highest unit sales. Products that tie must all appear.
CREATE TABLE categories ( category_id int PRIMARY KEY, name text NOT NULL ); CREATE TABLE products ( product_id int PRIMARY KEY, category_id int NOT NULL, name text NOT NULL ); CREATE TABLE order_items ( order_id int NOT NULL, product_id int NOT NULL, qty int NOT NULL, PRIMARY KEY (order_id, product_id) ); INSERT INTO categories (category_id, name) VALUES (1, 'Dairy'), (2, 'Snacks'); INSERT INTO products (product_id, category_id, name) VALUES (1, 1, 'Milk'), (2, 1, 'Curd'), (3, 1, 'Paneer'), (4, 1, 'Ghee'), (5, 2, 'Peanuts'), (6, 2, 'Banana chips'), (7, 2, 'Biscuits'); INSERT INTO order_items (order_id, product_id, qty) VALUES (1, 1, 6), (2, 1, 4), (1, 2, 7), (3, 3, 4), (9, 3, 3), (4, 4, 2), (5, 5, 5), (6, 6, 3), (7, 6, 2), (8, 7, 3);
Approach. First total the units per product. Then rank the products inside each category by units, highest first, with dense_rank, which gives tied products the same place and does not skip numbers. Keep places 1 and 2 in an outer query, since a window function cannot be filtered in the query that computes it.
WITH sold AS ( SELECT p.category_id, p.name, sum(oi.qty) AS units FROM products AS p JOIN order_items AS oi ON oi.product_id = p.product_id GROUP BY p.category_id, p.name ), ranked AS ( SELECT category_id, name, units, dense_rank() OVER ( PARTITION BY category_id ORDER BY units DESC ) AS place FROM sold ) SELECT c.name AS category, r.name AS product, r.units, r.place FROM ranked AS r JOIN categories AS c ON c.category_id = r.category_id WHERE r.place <= 2 ORDER BY c.name, r.place, r.name;
category | product | units | place ---------+--------------+-------+------ Dairy | Milk | 10 | 1 Dairy | Curd | 7 | 2 Dairy | Paneer | 7 | 2 Snacks | Banana chips | 5 | 1 Snacks | Peanuts | 5 | 1 Snacks | Biscuits | 3 | 2 (6 rows)
Why it works. Dairy has a tie at second place between curd and paneer, so both are kept, and the ghee in third place drops out. Snacks has a tie at first, so peanuts and banana chips both get place 1, and the biscuits take place 2 because dense_rank does not leave a gap. With row_number one of the tied products would have vanished, chosen by an undefined order. With rank the biscuits would be in place 3 and would be dropped. The last sort key, the product name, only fixes the printing order of the tied rows.
Part 2 · Round two: comparison and sequencing (30 minutes)
Before round two
Round two moves from counting to comparing. Every problem here needs a window function, and the usual way to lose time is to write the window function first and the grain second. Start from the other end instead. Decide which rows are being compared, a store day with the day before it, a salary with the other salaries in its store, an order with the order before it, and then write the step that makes those rows exist. The window function is the last, small step.
Two checks are worth the minute they take in this round. Ask what the first row of each group should show, because lag returns NULL there and you have to decide whether that is right. And ask where the boundary is, since "more than" and "at least" differ by one value, and the data of each problem has a row on the boundary on purpose.
Problem 4: change from the previous day
Brief. For each store, show the number of orders on each day that had orders, and the change from that store's previous day with orders. The first day of a store has no change.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE orders ( order_id int PRIMARY KEY, store_id int NOT NULL, placed_at timestamptz NOT NULL ); INSERT INTO orders (order_id, store_id, placed_at) VALUES (1, 1, '2026-03-02 09:00'), (2, 1, '2026-03-02 17:00'), (3, 1, '2026-03-03 11:00'), (4, 1, '2026-03-06 10:00'), (5, 1, '2026-03-06 12:00'), (6, 1, '2026-03-06 19:00'), (7, 2, '2026-03-02 08:00'), (8, 2, '2026-03-04 13:00'), (9, 2, '2026-03-05 14:00');
Approach. Aggregate first, because lag must look at one row per store and day, not at single orders. Count orders per store and day in a CTE, and then apply lag to the daily counts inside a window partitioned by store and ordered by day.
WITH daily AS ( SELECT store_id, placed_at::date AS day, count(*) AS orders FROM orders GROUP BY store_id, placed_at::date ) SELECT store_id, day::text AS day, orders, orders - lag(orders) OVER ( PARTITION BY store_id ORDER BY day ) AS change FROM daily ORDER BY store_id, day;
store_id | day | orders | change ---------+------------+--------+------- 1 | 2026-03-02 | 2 | NULL 1 | 2026-03-03 | 1 | -1 1 | 2026-03-06 | 3 | 2 2 | 2026-03-02 | 1 | NULL 2 | 2026-03-04 | 1 | 0 2 | 2026-03-05 | 1 | 0 (6 rows)
Why it works. Store 1 has no orders on 4 and 5 March, so the row after 3 March is 6 March, and its change of 2 is measured against 3 March, not against an empty day. That is what "previous day with orders" asks for. If the report needs calendar days, generate every day and left join, as in the first problem. The NULL in the first row of each store is correct, since there is nothing to compare with, and a coalesce to zero would claim that the change was nothing.
Problem 5: the second highest salary
Brief. For each store, find the second highest salary and the staff who earn it. A store with fewer than two different salaries has no second highest, so leave it out.
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, 'Dev', 1, 15000.00), (5, 'Farah', 2, 20000.00), (6, 'Kavita', 2, 20000.00), (7, 'Suresh', 3, 55000.00), (8, 'Meenal', 3, 90000.00);
Approach. "Second highest" refers to distinct salary values, not to the second row. Rank the salaries inside each store with dense_rank in descending order, keep place 2, and then collect the names that share that salary with string_agg, ordered by name so that the output is fixed.
SELECT store_id, salary, string_agg(name, ', ' ORDER BY name) AS who FROM ( SELECT store_id, name, salary, dense_rank() OVER ( PARTITION BY store_id ORDER BY salary DESC ) AS place FROM staff ) AS ranked WHERE place = 2 GROUP BY store_id, salary ORDER BY store_id;
store_id | salary | who ---------+----------+------- 1 | 22000.00 | Arjun 3 | 55000.00 | Suresh (2 rows)
Why it works. Store 1 has two staff on 23,000 rupees, so a plain second row would be the other person on the same salary. With dense_rank the salaries 23,000, 22,000 and 15,000 get places 1, 2 and 3, and the answer is 22,000 for Arjun. Store 2 pays everybody 20,000, so no place 2 exists and the store disappears, as asked. The same query with LIMIT 1 OFFSET 1 would have been wrong in all three ways: ties, missing second values and per-store grouping.
Problem 6: customers who came back after a break
Brief. List every order that was placed more than 7 days after the same customer's previous order, and show how many days it was.
CREATE TABLE orders ( order_id int PRIMARY KEY, customer_id int NOT NULL, placed_at date NOT NULL ); INSERT INTO orders (order_id, customer_id, placed_at) VALUES (1, 1, '2026-03-01'), (2, 1, '2026-03-04'), (3, 1, '2026-03-20'), (4, 2, '2026-03-02'), (5, 2, '2026-03-09'), (6, 2, '2026-03-17'), (7, 3, '2026-03-05'), (8, 3, '2026-03-30');
Approach. This is a gap, so compare each row with the row before it for the same customer. Subtracting two date values gives a whole number of days. Use lag over a window partitioned by customer and ordered by date, with the order id as tiebreaker, and filter in the outer query.
SELECT customer_id, order_id, placed_at::text AS placed_at, days_since_previous FROM ( SELECT customer_id, order_id, placed_at, placed_at - lag(placed_at) OVER ( PARTITION BY customer_id ORDER BY placed_at, order_id ) AS days_since_previous FROM orders ) AS gaps WHERE days_since_previous > 7 ORDER BY customer_id, placed_at;
customer_id | order_id | placed_at | days_since_previous ------------+----------+------------+-------------------- 1 | 3 | 2026-03-20 | 16 2 | 6 | 2026-03-17 | 8 3 | 8 | 2026-03-30 | 25 (3 rows)
Why it works. Customer 2 has gaps of 7 and 8 days. The 7 is not more than 7, so only the order after the 8-day gap appears, which tests the boundary. The first order of each customer has a NULL gap, and a comparison with NULL is not true, so it is never listed, which is the right behaviour since nothing came before it. If you use timestamptz instead of date, the subtraction gives an interval, and you compare it with interval '7 days'.
Why must problem 4 aggregate before applying lag?
- Without aggregation
lagwould compare single orders, so the previous row would be the previous order, not the previous day. - Counting per store and day gives one row per day, and
lagthen compares days.
Why does the 7-day gap of customer 2 not appear in problem 6?
Part 3 · Round three: mixed problems and what to practise next (30 minutes)
Problem 7: products under each top category
Brief. For each top-level category, count the products in it and in all of the categories beneath it, at any depth.
CREATE TABLE categories ( category_id int PRIMARY KEY, name text NOT NULL, parent_id int REFERENCES categories (category_id) ); CREATE TABLE products ( product_id int PRIMARY KEY, name text NOT NULL, category_id int NOT NULL REFERENCES categories (category_id) ); INSERT INTO categories (category_id, name, parent_id) VALUES (1, 'Groceries', NULL), (2, 'Dairy', 1), (3, 'Staples', 1), (4, 'Rice', 3), (5, 'Home care', NULL), (6, 'Cleaners', 5), (7, 'Spices', 3); INSERT INTO products (product_id, name, category_id) VALUES (1, 'Milk', 2), (2, 'Curd', 2), (3, 'Basmati', 4), (4, 'Sona masoori', 4), (5, 'Floor cleaner', 6), (6, 'Turmeric', 7), (7, 'Salt', 3);
Approach. Walk the tree with a recursive CTE that carries the top-level ancestor, called root_id, down to every descendant, starting each walk from a root. Then join the products to the visited categories and group by the root. A left join keeps a root with no products.
WITH RECURSIVE tree (root_id, category_id) AS ( SELECT category_id, category_id FROM categories WHERE parent_id IS NULL UNION ALL SELECT t.root_id, c.category_id FROM categories AS c JOIN tree AS t ON c.parent_id = t.category_id ) SELECT r.name AS top_category, count(p.product_id) AS products FROM tree AS t JOIN categories AS r ON r.category_id = t.root_id LEFT JOIN products AS p ON p.category_id = t.category_id GROUP BY r.category_id, r.name ORDER BY r.name;
top_category | products -------------+--------- Groceries | 6 Home care | 1 (2 rows)
Why it works. The recursive term only joins the children of the rows from the last round, and keeps the same root_id, so every category inside a tree ends up labelled with its root. Groceries gets Dairy, Staples, Rice and Spices, which hold six products in all, and Home care gets one. A product placed directly on a mid-level category, like salt in Staples, is counted too, because the join looks at every visited category and not only at the leaves.
Problem 8: a wide table of statuses
Brief. Show one row per store with a column for each order status and a column for the total.
CREATE TABLE orders ( order_id int PRIMARY KEY, store_id int NOT NULL, status text NOT NULL ); INSERT INTO orders (order_id, store_id, status) VALUES (1, 1, 'delivered'), (2, 1, 'delivered'), (3, 1, 'cancelled'), (4, 1, 'placed'), (5, 2, 'delivered'), (6, 2, 'delivered'), (7, 2, 'delivered'), (8, 3, 'cancelled'), (9, 3, 'placed'), (10, 3, 'placed');
Approach. This is a pivot. Group by store and write one conditional count for each status. count(*) FILTER (WHERE ...) returns 0 for a status that does not occur, which is the right value for a count.
SELECT store_id, count(*) FILTER (WHERE status = 'placed') AS placed, count(*) FILTER (WHERE status = 'delivered') AS delivered, count(*) FILTER (WHERE status = 'cancelled') AS cancelled, count(*) AS total FROM orders GROUP BY store_id ORDER BY store_id;
store_id | placed | delivered | cancelled | total ---------+--------+-----------+-----------+------ 1 | 1 | 2 | 1 | 4 2 | 0 | 3 | 0 | 3 3 | 2 | 0 | 1 | 3 (3 rows)
Why it works. Store 2 has no placed or cancelled orders, and the table shows zeros, not NULLs, because a count of no rows is 0. The total comes from an unfiltered count(*) in the same group, so the three status columns must add up to it. That check catches a status that you forgot to list, which would otherwise be dropped without any error. The status list is written into the query, so a new status needs a new column.
Problem 9: customers of every store
Brief. Find the customers who have ordered from every store, not only from some of them.
CREATE TABLE stores ( store_id int PRIMARY KEY, name text NOT NULL ); 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), store_id int NOT NULL REFERENCES stores (store_id) ); INSERT INTO stores (store_id, name) VALUES (1, 'Kothrud'), (2, 'Baner'), (3, 'Wakad'); INSERT INTO customers (customer_id, name) VALUES (1, 'Asha'), (2, 'Ravi'), (3, 'Meera'); INSERT INTO orders (order_id, customer_id, store_id) VALUES (1, 1, 1), (2, 1, 2), (3, 1, 3), (4, 1, 1), (5, 2, 1), (6, 2, 2), (7, 2, 2), (8, 3, 3);
Approach. This is the relational division pattern from the relational model chapter. A customer qualifies when the number of different stores they ordered from equals the number of all stores. Count distinct stores per customer, and compare with a subquery that counts the stores table.
SELECT c.name, count(DISTINCT o.store_id) AS stores_used FROM customers AS c JOIN orders AS o ON o.customer_id = c.customer_id GROUP BY c.customer_id, c.name HAVING count(DISTINCT o.store_id) = (SELECT count(*) FROM stores) ORDER BY c.name;
name | stores_used -----+------------ Asha | 3 (1 row)
Why it works. Asha ordered from all three stores, one of them twice, so her distinct count is 3. Ravi used two stores and Meera one. count(DISTINCT ...) is essential, because Asha's four orders would otherwise be compared with three stores. The subquery makes the query follow the data: when a fourth store opens, nobody qualifies until they order from it, and no edit is needed.
What to practise next
These nine problems touch the main patterns once each, and not every variation. To get fluent, solve more of them on data you have not seen. The public database problem set on LeetCode has many SQL problems, and the names below are patterns to look for in its titles and tags. Do not copy a solution, write yours and compare it with the shape of the pattern.
- Aggregation: orders per status or day, buckets with a zero for empty periods, running totals, and subtotals.
- Filtering: customers who never ordered, who ordered in every month, and who ordered a product and never another.
- Top-N per group: the highest salary per department, the top three per category, and duplicates to remove.
- Comparison: rows above their group average, change from the previous period, and employees who earn more than their manager.
- Sequencing: consecutive days, sessions with a time gap, and the nth order of each user.
- Hierarchy: all reports under a manager, the depth of each node, and the path from a node to its root.
- Transformation: a pivot of months into columns, an unpivot of columns into rows, and string aggregation.
When you practise, keep to the habits from the round introduction. State the grain. Build the query in CTE steps. Test it on a few rows that include a tie, a NULL and an empty group. A solution that works only on the happy path is wrong on exactly the rows that matter, and a tie, a NULL and an empty group are where it breaks.
In problem 9, why is count(DISTINCT store_id) compared with a subquery and not with the number 3?
- The subquery follows the data, so the query stays right when a store is added or closed.
- A hard-coded 3 would silently give wrong answers after any change.
Why does problem 7 left join the products to the visited categories?
- A top-level category with no products anywhere beneath it would otherwise vanish instead of showing a count of 0.
All chapters · Previous: Transformation Patterns: Pivoting, Unpivoting, Text and JSON