Courses / Databases for Backend Interviews / Chapter 10
Module 6 · SQL patterns: aggregation and filtering · Chapter 10 of 27
SQL Query Patterns: A Pattern Map and the Practice Schema
Builds on SQL Essentials: Tables, Changes, Queries, Joins, Subqueries and Views and Normalisation: Anomalies, 1NF to BCNF, and When to Denormalise. Next up: Aggregation Patterns: Tally Counts, Group Buckets and Rolling Totals.
Part 1 · What a query pattern is
A shape you meet again
A query pattern is a reusable shape of solution to a question that keeps coming back in new clothes. Once you can name the shape, most of the SQL writes itself.
Most database questions look new, but the work behind them repeats. "Which customers did not order last month?", "Which products are not sold in Chennai?" and "Which stores have no staff?" are one question: keep the rows of one set that have no match in another set. That shape has a name, an anti-join, and you write it the same few ways every time. A query pattern is such a shape together with the handful of SQL constructs that implement it.
Patterns earn their place for three reasons.
- They shorten the step from reading a question to typing the first line of a query.
- They tell you where the bugs hide. Every pattern has a known trap: ties, NULLs, an empty group, a duplicate that a join multiplies.
- They make solutions comparable. Two people who see the same shape reach for the same tools, so a reviewer can read the query by recognising it.
A pattern is not a trick or a one-line formula. It is a way of breaking a question into a few steps that you already know how to write: pick the rows, group them or number them, compare them, and shape the output.
The five families
The patterns in the next chapters fall into five families. Each family is a kind of question, and each kind of question has words that give it away.
| Family | The question sounds like | Main tools |
|---|---|---|
| Aggregation | how many, total, per day, running total, share of the whole | GROUP BY, aggregates, FILTER, ROLLUP, window sums |
| Filtering | who has no, at least one, top 3 in each, duplicates | EXISTS, NOT EXISTS, HAVING, ROW_NUMBER, DISTINCT ON |
| Comparison | above the average, compared with yesterday, earns more than the manager | self-joins, LAG and LEAD, window averages, subqueries |
| Sequencing and hierarchy | streak, session, first and last, everyone under a manager | ROW_NUMBER, gaps and islands, recursive CTEs |
| Transformation | one column per month, split the text, return as JSON | FILTER pivots, unnest, string and JSON functions |
The words in the middle column are the clues. "Per" almost always means GROUP BY or a window with PARTITION BY. "Never", "none" and "not" point to exclusion. "In a row", "consecutive" and "gap" point to sequencing. "Than" points to comparison, because something is being set against something else. "Every level" or "all the way up" points to a recursive CTE.
Families overlap, and real questions combine them. "The top two products by revenue in each city" needs aggregation to get revenue and filtering to keep the top two per group. Treat the clue words as a first guess, then check the guess against a tiny example before you write the full query.
One query from each family
Here is one query from each family on the smallest table that can show it: three rows, one for each purchase. mini is a throwaway table, not part of the practice schema that comes later in this chapter. Results are printed with the helper from the SQL chapter, which writes NULL where a value is missing. The helper prints a date as a UTC timestamp, so the queries cast dates to text.
CREATE TABLE mini ( customer text NOT NULL, day date NOT NULL, amount int NOT NULL ); INSERT INTO mini (customer, day, amount) VALUES ('Asha', '2026-03-01', 200), ('Asha', '2026-03-02', 350), ('Ravi', '2026-03-01', 120);
SELECT customer, day::text AS day, amount FROM mini ORDER BY day, customer;
customer | day | amount ---------+------------+------- Asha | 2026-03-01 | 200 Ravi | 2026-03-01 | 120 Asha | 2026-03-02 | 350 (3 rows)
Aggregation collapses rows into one row per group. Filtering keeps some rows and drops the rest. Here are those two.
SELECT customer, sum(amount) AS total, count(*) AS orders FROM mini GROUP BY customer ORDER BY customer;
customer | total | orders ---------+-------+------- Asha | 550 | 2 Ravi | 120 | 1 (2 rows)
SELECT customer, day::text AS day, amount FROM mini ORDER BY amount DESC LIMIT 1;
customer | day | amount ---------+------------+------- Asha | 2026-03-02 | 350 (1 row)
Comparison and sequencing both use a window function, which computes a value for each row from related rows without collapsing them. lag reads the previous row inside the partition, and row_number numbers the rows.
SELECT customer, day::text AS day, amount, amount - lag(amount) OVER (PARTITION BY customer ORDER BY day) AS change FROM mini ORDER BY customer, day;
customer | day | amount | change ---------+------------+--------+------- Asha | 2026-03-01 | 200 | NULL Asha | 2026-03-02 | 350 | 150 Ravi | 2026-03-01 | 120 | NULL (3 rows)
SELECT customer, day::text AS day, row_number() OVER (PARTITION BY customer ORDER BY day) AS nth_order FROM mini ORDER BY customer, day;
customer | day | nth_order ---------+------------+---------- Asha | 2026-03-01 | 1 Asha | 2026-03-02 | 2 Ravi | 2026-03-01 | 1 (3 rows)
Reshaping, and what to take away
Transformation changes the shape of the result without changing the facts. Here the two days become two columns, one per date. Ravi has no purchase on 2 March, so that cell is NULL, not 0.
SELECT customer, sum(amount) FILTER (WHERE day = '2026-03-01') AS mar_1, sum(amount) FILTER (WHERE day = '2026-03-02') AS mar_2 FROM mini GROUP BY customer ORDER BY customer;
customer | mar_1 | mar_2 ---------+-------+------ Asha | 200 | 350 Ravi | 120 | NULL (2 rows)
Five families, five small queries, the same three rows. The data did not change; the question did. That is the point of the families: they describe the question, not the table.
Notice what the comparison query showed. Asha's first row has a change of NULL, because there is no earlier row to subtract. A pattern carries its edge case with it, and the later chapters name the edge case of every pattern when they teach it.
A question asks for customers who have never ordered. Which family is it, and which construct do you reach for first?
- Filtering, in its exclusion form (an anti-join).
NOT EXISTS, or aLEFT JOINfollowed byWHERE ... IS NULLon the right side.
In the comparison query above, why is the change NULL for the first row of each customer?
laglooks one row back inside the partition, and the first row of a partition has no row before it.- The window function returns NULL there, and subtracting from NULL gives NULL, as the run shows.
Why can the same three rows illustrate five different families?
- A family describes the shape of the question, not the shape of the table.
- Different clause combinations turn the same rows into totals, a single row, a difference, a number or a pivot.
Part 2 · Patterns by kind of work
Three kinds of work
The same families show up with different weights depending on what the SQL is for. Here are three kinds of work, described by what the code does, with the families each one leans on.
| Kind of work | What the query is for | Leans on |
|---|---|---|
| Product backend | answer one user's request fast: their latest order, whether a coupon was used, their position in a list | filtering (latest per group, existence), a little sequencing |
| Reporting and dashboards | summarise many rows for a person to read: revenue per day, city totals, growth against last month | aggregation, comparison, transformation (pivots) |
| Data pipelines | clean and move data between systems: remove duplicates from a re-sent file, reshape rows for a warehouse | filtering (duplicates), sequencing, transformation |
This is a description of the work, not a ranking. A backend engineer writes reports too, and a pipeline often ends in a total. The table tells you which tools to practise first for the job in front of you.
The kinds of work also differ in what counts as a good query. A backend query runs thousands of times a minute, so it must touch few rows and use an index. A report runs a few times a day over many rows, so it can afford a scan but must be exactly right about edge cases. A pipeline runs once over a batch, so what matters is that running it twice gives the same result. Keep these three questions in mind as the examples go by: how often, how many rows, and what happens on a repeat.
Each example below uses a small throwaway table, again not the practice schema. mini now has five rows: purchases by three customers over three days. If you ran the previous lesson in the same database, drop its three-row mini first with DROP TABLE mini;.
A product backend: the latest order per customer
A profile screen shows the last purchase of each customer. In pattern terms this is top-1 per group, a filtering pattern. PostgreSQL has a construct built for it: DISTINCT ON, which keeps the first row of each group in the order you give.
CREATE TABLE mini ( customer text NOT NULL, day date NOT NULL, amount int NOT NULL ); INSERT INTO mini (customer, day, amount) VALUES ('Asha', '2026-03-01', 200), ('Asha', '2026-03-02', 350), ('Ravi', '2026-03-01', 120), ('Ravi', '2026-03-03', 90), ('Meera', '2026-03-02', 400);
SELECT DISTINCT ON (customer) customer, day::text AS last_day, amount FROM mini ORDER BY customer, day DESC;
customer | last_day | amount ---------+------------+------- Asha | 2026-03-02 | 350 Meera | 2026-03-02 | 400 Ravi | 2026-03-03 | 90 (3 rows)
The ORDER BY decides which row survives: the day is descending, so the newest row of each customer comes first and DISTINCT ON keeps it. The leading expression of the ORDER BY must match the DISTINCT ON expression, or PostgreSQL raises an error. DISTINCT ON is a PostgreSQL feature, not standard SQL. A later chapter in this part shows the portable form with ROW_NUMBER, which is also the one you need when you want the top two rows instead of the top one.
Reporting: totals with a grand total row
A dashboard wants revenue per day and a grand total underneath. That is aggregation with subtotals. GROUP BY ROLLUP (day) adds one extra row for the whole set.
SELECT day::text AS day, sum(amount) AS revenue FROM mini GROUP BY ROLLUP (day) ORDER BY day;
day | revenue -----------+-------- 2026-03-01 | 320 2026-03-02 | 750 2026-03-03 | 90 NULL | 1160 (4 rows)
The last row is the grand total, and its day is NULL because it stands for all days. That NULL is a trap. If a real day could also be NULL, you could not tell the two apart, and a later chapter in this part shows the GROUPING function that settles it.
Also notice ORDER BY day. Without it the order of the rows is not defined, and a NULL sorts last in ascending order, which happens to put the total at the bottom here. Say what you rely on. A report that depends on an unstated sort order breaks the day someone adds a row that sorts differently.
A pipeline: duplicates in a re-sent file
A nightly file is sometimes loaded twice, or an order is re-sent with a corrected amount. The landing table now holds two rows for order 101. The pipeline must keep the latest row per order. This is again top-1 per group, now written with ROW_NUMBER.
CREATE TABLE landing ( order_ref int NOT NULL, amount int NOT NULL, loaded_at timestamptz NOT NULL ); INSERT INTO landing (order_ref, amount, loaded_at) VALUES (101, 500, '2026-03-02 01:00'), (102, 250, '2026-03-02 01:00'), (101, 520, '2026-03-02 02:00'), (103, 90, '2026-03-02 02:00');
SELECT order_ref, amount FROM ( SELECT order_ref, amount, row_number() OVER (PARTITION BY order_ref ORDER BY loaded_at DESC) AS rn FROM landing ) AS ranked WHERE rn = 1 ORDER BY order_ref;
order_ref | amount ----------+------- 101 | 520 102 | 250 103 | 90 (3 rows)
Order 101 appears once, with the later amount 520. The inner query numbers each order's rows from the newest, and the outer query keeps number 1. If two rows had the same loaded_at, the numbering between them would be arbitrary, so a real pipeline adds a tiebreaker such as a load id to the ORDER BY.
Which kind of work leans most on top-1-per-group, and why does it appear in two of the three examples?
- It shows up in the backend (latest order of each customer) and in the pipeline (latest row per order).
- Both ask for one row per key chosen by an ordering, which is the same filtering shape.
What does the NULL in the day column of the ROLLUP result mean?
- It marks the grand total row: the group that stands for every day.
- It is ambiguous if the real data can contain NULL days, which
GROUPINGresolves.
Why does the pipeline query need a tiebreaker in a real system?
ROW_NUMBERstill numbers rows when two have the sameloaded_at, but which gets 1 is arbitrary.- Adding a unique column to the
ORDER BYmakes the choice repeatable.
Part 3 · The practice schema
A grocery delivery service
Every pattern chapter after this one uses the same business: an online grocery delivery service in several Indian cities. Customers place orders at the store that serves them, and an order has lines, one for each product bought. You will recognise the shape from any delivery app, and its tables are enough to ask every kind of question in the five families.
| Table | One row is | Grain and keys |
|---|---|---|
| cities | a city | city_id |
| stores | a store in a city | store_id, city_id |
| customers | a person who signed up | customer_id, city_id |
| categories | a product category, in a tree | category_id, parent_id |
| products | something we sell | product_id, category_id |
| orders | one order | order_id, customer_id, store_id |
| order_items | one product on one order | (order_id, product_id) |
| staff | an employee, in a reporting tree | staff_id, manager_id |
| app_events | one tap in the app | no key: events repeat |
The grain of a table is what one row stands for. Knowing the grain is the first step of every query in this course, because a join between two tables of different grain multiplies rows, and an aggregate over the wrong grain double counts. orders has one row per order, order_items one row per order and product, so joining them turns one order row into as many rows as the order has lines.
The CREATE TABLE script
The script starts with SET TIME ZONE 'Asia/Kolkata' so that every timestamp is read and printed in Indian Standard Time. Times are stored as timestamptz, which keeps an exact instant (PostgreSQL stores it in UTC and converts to the session time zone on display). Money is numeric(10,2), never a floating-point type, because a rupee amount must add up exactly.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE cities ( city_id int PRIMARY KEY, name text NOT NULL, state text NOT NULL ); CREATE TABLE stores ( store_id int PRIMARY KEY, city_id int NOT NULL REFERENCES cities (city_id), name text NOT NULL, opened_on date NOT NULL ); CREATE TABLE customers ( customer_id int PRIMARY KEY, name text NOT NULL, city_id int NOT NULL REFERENCES cities (city_id), signed_up_at timestamptz NOT NULL ); 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, category_id int NOT NULL REFERENCES categories (category_id), name text NOT NULL, price numeric(10,2) 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), placed_at timestamptz NOT NULL, status text NOT NULL CHECK (status IN ('placed', 'delivered', 'cancelled')) );
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) ); CREATE TABLE staff ( staff_id int PRIMARY KEY, name text NOT NULL, store_id int NOT NULL REFERENCES stores (store_id), manager_id int REFERENCES staff (staff_id), role text NOT NULL, salary numeric(10,2) NOT NULL ); CREATE TABLE app_events ( customer_id int NOT NULL REFERENCES customers (customer_id), event_at timestamptz NOT NULL, event_type text NOT NULL );
Three small points about the script. order_items stores its own unit_price as well as the products.price, because the price on an order must stay what the customer paid even after the catalogue price changes; the normalisation chapter calls this a snapshot. The status column is guarded by a CHECK so that a typo cannot create a fourth status. And categories and staff each point at their own table, which makes them trees; a later chapter in this part walks them with recursive queries.
Sample rows and a first check
Each pattern chapter creates only the tables it needs and fills them with its own small dataset, so no chapter depends on another. This chapter loads a little of everything, 10 orders in March 2026, so that you can see every table once. Every INSERT names its columns.
INSERT INTO cities (city_id, name, state) VALUES (1, 'Pune', 'Maharashtra'), (2, 'Hyderabad', 'Telangana'), (3, 'Chennai', 'Tamil Nadu'); INSERT INTO stores (store_id, city_id, name, opened_on) VALUES (1, 1, 'Kothrud', '2024-02-10'), (2, 1, 'Viman Nagar', '2024-08-01'), (3, 2, 'Madhapur', '2024-05-15'), (4, 3, 'Adyar', '2025-01-20'); INSERT INTO customers (customer_id, name, city_id, signed_up_at) VALUES (1, 'Asha', 1, '2025-11-03 10:00'), (2, 'Ravi', 1, '2025-12-14 18:30'), (3, 'Meera', 2, '2026-01-09 09:15'), (4, 'Karthik', 2, '2026-01-21 20:00'), (5, 'Divya', 3, '2026-02-02 12:45'), (6, 'Imran', 3, '2026-02-18 08:20'), (7, 'Sunita', 1, '2026-02-25 16:10'), (8, 'Naveen', 2, '2026-03-01 11:00'); INSERT INTO categories (category_id, name, parent_id) VALUES (1, 'Grocery', NULL), (2, 'Dairy', 1), (3, 'Staples', 1), (4, 'Snacks', 1), (5, 'Milk and curd', 2), (6, 'Rice and flour', 3);
INSERT INTO products (product_id, category_id, name, price) VALUES (1, 5, 'Toned milk 1 L', 58.00), (2, 5, 'Curd 500 g', 40.00), (3, 2, 'Paneer 200 g', 95.00), (4, 6, 'Basmati rice 5 kg', 640.00), (5, 6, 'Wheat flour 5 kg', 245.00), (6, 3, 'Toor dal 1 kg', 165.00), (7, 4, 'Salted peanuts 200 g', 70.00), (8, 4, 'Banana chips 150 g', 85.00); INSERT INTO orders (order_id, customer_id, store_id, placed_at, status) VALUES (1, 1, 1, '2026-03-02 09:15', 'delivered'), (2, 2, 1, '2026-03-02 18:40', 'delivered'), (3, 3, 3, '2026-03-03 11:05', 'delivered'), (4, 1, 2, '2026-03-04 20:30', 'cancelled'), (5, 4, 3, '2026-03-05 08:50', 'delivered'), (6, 5, 4, '2026-03-05 19:10', 'delivered'), (7, 2, 1, '2026-03-06 10:00', 'delivered'), (8, 6, 4, '2026-03-07 13:25', 'placed'), (9, 3, 3, '2026-03-09 17:45', 'delivered'), (10, 1, 1, '2026-03-10 07:55', 'placed');
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), (2, 7, 2, 70.00), (3, 3, 1, 95.00), (3, 6, 2, 165.00), (4, 5, 1, 245.00), (5, 1, 4, 58.00), (5, 8, 1, 85.00), (6, 4, 1, 640.00), (6, 2, 2, 40.00), (7, 6, 1, 165.00), (7, 3, 2, 95.00), (8, 7, 3, 70.00), (8, 8, 2, 85.00), (9, 1, 2, 58.00), (9, 5, 1, 245.00), (10, 2, 1, 40.00), (10, 3, 1, 95.00); INSERT INTO staff (staff_id, name, store_id, manager_id, role, salary) VALUES (1, 'Lakshmi', 1, NULL, 'manager', 52000.00), (2, 'Rohit', 1, 1, 'picker', 21000.00), (3, 'Farah', 1, 1, 'rider', 23000.00), (4, 'Gopal', 3, NULL, 'manager', 48000.00), (5, 'Tanvi', 3, 4, 'picker', 22000.00), (6, 'Ajay', 4, NULL, 'manager', 50000.00); INSERT INTO app_events (customer_id, event_at, event_type) VALUES (1, '2026-03-02 09:00', 'open_app'), (1, '2026-03-02 09:05', 'add_to_cart'), (1, '2026-03-02 09:15', 'checkout'), (2, '2026-03-02 18:20', 'open_app'), (2, '2026-03-02 18:40', 'checkout'), (3, '2026-03-03 10:50', 'open_app'), (3, '2026-03-03 11:05', 'checkout'), (3, '2026-03-03 15:00', 'open_app'), (4, '2026-03-05 08:40', 'open_app'), (4, '2026-03-05 08:50', 'checkout');
Keys keep lines unique
The grain of order_items is one row per order and product, and the composite primary key (order_id, product_id) enforces it. Here is the check on the grain: 19 lines across 10 orders.
SELECT count(*) AS lines, count(DISTINCT order_id) AS orders, sum(qty * unit_price) AS line_revenue FROM order_items;
lines | orders | line_revenue ------+--------+------------- 19 | 10 | 3954.00 (1 row)
Inserting the same product on the same order a second time fails with SQLSTATE 23505, so a line cannot be duplicated by accident. Quantity goes up by updating qty, not by adding a row.
INSERT INTO order_items (order_id, product_id, qty, unit_price) VALUES (1, 1, 1, 58.00);
ERROR 23505: duplicate key value violates unique constraint "order_items_pkey"
This is why the later chapters can trust the grain. When a query returns more rows than expected, the cause is a join, not a duplicated line.
What is the grain of order_items, and what happens to an orders row that is joined to it?
- One row per product on an order.
- The order row is repeated once for each line the order has, so a sum over an order column would count it several times.
Why does order_items keep its own unit_price when products already has a price?
- The price on a past order must not change when the catalogue price changes later.
- The line stores the price the customer paid, a snapshot taken at order time.
Why is placed_at a timestamptz and shown in Asia/Kolkata?
timestamptzstores one exact instant, so a comparison does not depend on where the reader is.- The session time zone only decides how the instant is displayed, so day boundaries fall on Indian midnight.
Part 4 · A refresher in ten queries
Counting and joining
This lesson runs ten short queries on the schema above, one idea each. If every line reads easily, you are ready for the pattern chapters. If one does not, read the SQL chapter again for that idea. The first three are about grouping and joining. Every query is run on the schema from the previous lesson, and the ORDER BY in each makes its output order repeatable.
Count by group. GROUP BY turns many rows into one row per value, and an aggregate such as count(*) summarises each group. Here is the number of orders in each status.
SELECT status, count(*) AS orders FROM orders GROUP BY status ORDER BY orders DESC, status;
status | orders ----------+------- delivered | 7 placed | 2 cancelled | 1 (3 rows)
Join, group and HAVING. A join glues rows of two tables by a condition. Orders know their store and a store knows its city, so two joins count orders per city. HAVING filters groups after they are formed, the way WHERE filters rows before. Chennai has two orders, so it is dropped.
SELECT c.name AS city, count(*) AS orders FROM orders AS o JOIN stores AS s ON s.store_id = o.store_id JOIN cities AS c ON c.city_id = s.city_id GROUP BY c.name HAVING count(*) >= 3 ORDER BY orders DESC, city;
city | orders ----------+------- Pune | 5 Hyderabad | 3 (2 rows)
Join and aggregate over lines. Order 1 has two lines: 2 packs of milk at 58 and one 5 kg rice bag at 640, which is 756. The WHERE keeps delivered orders only, so the cancelled order 4 and the two orders still placed are absent. A reader who forgets the filter would count orders that never reached the customer, which is the most common slip in revenue queries.
SELECT o.order_id, sum(i.qty * i.unit_price) AS order_total FROM orders AS o JOIN order_items AS i ON i.order_id = o.order_id WHERE o.status = 'delivered' GROUP BY o.order_id ORDER BY o.order_id;
order_id | order_total ---------+------------ 1 | 756.00 2 | 260.00 3 | 425.00 5 | 317.00 6 | 720.00 7 | 355.00 9 | 361.00 (7 rows)
Branching, missing rows and existence
Branch with CASE. CASE is an expression, so it can sit in a SELECT list, a GROUP BY or an ORDER BY. It tests its conditions in order and returns the first match, and returns NULL when nothing matches and there is no ELSE. Prices below 50 are cheap here, below 200 regular, and everything else premium.
SELECT name, price, CASE WHEN price < 50 THEN 'cheap' WHEN price < 200 THEN 'regular' ELSE 'premium' END AS band FROM products ORDER BY price;
name | price | band ---------------------+--------+-------- Curd 500 g | 40.00 | cheap Toned milk 1 L | 58.00 | regular Salted peanuts 200 g | 70.00 | regular Banana chips 150 g | 85.00 | regular Paneer 200 g | 95.00 | regular Toor dal 1 kg | 165.00 | regular Wheat flour 5 kg | 245.00 | premium Basmati rice 5 kg | 640.00 | premium (8 rows)
Find what has no match. A LEFT JOIN keeps every left row and fills the right side with NULL when nothing matches. Filtering on that NULL leaves the customers with no orders. Two customers signed up and have not ordered yet. The same question can be written with NOT EXISTS or NOT IN, and a later chapter in this part compares the three, including the case where NOT IN silently returns nothing.
SELECT c.name FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.customer_id WHERE o.order_id IS NULL ORDER BY c.name;
name
------
Naveen
Sunita
(2 rows)Test for existence. EXISTS asks whether a subquery returns at least one row, and it stops at the first. Here it finds the customers with a cancelled order. The subquery refers to the outer row c, which makes it a correlated subquery. Only Asha has a cancelled order, so she is the only name.
SELECT name FROM customers AS c WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id AND o.status = 'cancelled');
name
----
Asha
(1 row)Windows, CTEs and recursion
Number rows inside a group. A window function computes over a set of related rows and keeps every row in the result. PARTITION BY splits the rows into groups for the window, and ORDER BY inside it orders each group. Here each customer's orders are numbered from the oldest.
SELECT customer_id, order_id, row_number() OVER (PARTITION BY customer_id ORDER BY placed_at) AS nth FROM orders ORDER BY customer_id, nth;
customer_id | order_id | nth ------------+----------+---- 1 | 1 | 1 1 | 4 | 2 1 | 10 | 3 2 | 2 | 1 2 | 7 | 2 3 | 3 | 1 3 | 9 | 2 4 | 5 | 1 5 | 6 | 1 6 | 8 | 1 (10 rows)
Running count. With ORDER BY and no explicit frame, the window grows from the first row up to the current row and its peers. This is a running count of the orders of the Kothrud store.
SELECT placed_at::date::text AS day, order_id, count(*) OVER (ORDER BY placed_at) AS orders_so_far FROM orders WHERE store_id = 1 ORDER BY placed_at;
day | order_id | orders_so_far -----------+----------+-------------- 2026-03-02 | 1 | 1 2026-03-02 | 2 | 2 2026-03-06 | 7 | 3 2026-03-10 | 10 | 4 (4 rows)
Name an intermediate result. A common table expression, written WITH name AS (...), gives a subquery a name so the main query reads top to bottom. Here the CTE totals each order, and the main query averages those totals: a basket averages about 395 rupees, and the biggest is 756 rupees. All ten orders count here, including the cancelled one, because this query did not filter on status.
WITH totals AS ( SELECT order_id, sum(qty * unit_price) AS order_total FROM order_items GROUP BY order_id ) SELECT round(avg(order_total), 2) AS average_basket, max(order_total) AS biggest FROM totals;
average_basket | biggest ---------------+-------- 395.40 | 756.00 (1 row)
Walk a tree. A recursive CTE starts from the root rows and repeatedly joins the previous step to its children until none are left. This builds a path for every category from the top of the tree. The first part of the query picks the root, the part after UNION ALL joins each category to its parent in the previous step, and a later chapter in this part explains the evaluation order in detail.
All chapters · Previous: SQL Essentials: Tables, Changes, Queries, Joins, Subqueries and Views