Courses / Databases for Backend Interviews / Chapter 13
Module 7 · SQL patterns: comparing, sequencing and reshaping · Chapter 13 of 27
Comparison Patterns: Row Against Group, Neighbour and Earlier Period
Builds on Aggregation Patterns: Tally Counts, Group Buckets and Rolling Totals and Filtering Patterns: Existence, Exclusion, Aggregate Filters and Top-N per Group. Next up: Sequencing and Hierarchy Patterns: Streaks, Sessions and Recursive Trees.
Part 1 · Row against its group
Comparing a value with a benchmark
Many business questions compare a row with a benchmark: a product dearer than its category average, a store above the city's revenue, a sale bigger than usual. The benchmark is itself an aggregate, so the query has to see the row and the aggregate at once.
A comparison pattern sets one value against another value that comes from somewhere else in the data. The other value may be the average of the group the row belongs to, the value in the previous row, the value in a related row, or the same period a year ago. This chapter covers each, starting with the group.
The simplest case has an obvious wrong answer. If you write WHERE price > avg(price), PostgreSQL refuses, because an aggregate over all rows cannot be used in WHERE, where rows are being filtered one by one. Two correct ways exist. A correlated subquery computes the average for each row. A window function computes the average once per group and attaches it to every row of the group.
The data for this chapter uses seven tables from the patterns introduction: cities, stores, customers, categories, products, orders and staff. There are ten products in three categories, ten staff in three stores, fifteen customers who signed up from January 2025 to March 2026, and fifteen orders in the first week of March 2026.
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 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 );
The data
The rows are small enough to check by hand. Prices are in rupees. Two staff earn the same in two stores, and one person earns more than their manager, so the later lessons have ties and an odd case to find.
INSERT INTO cities (city_id, name, state) VALUES (1, 'Pune', 'Maharashtra'), (2, 'Hyderabad', 'Telangana'); 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'); INSERT INTO customers (customer_id, name, city_id, signed_up_at) VALUES (1, 'Asha', 1, '2025-01-12 10:00'), (2, 'Ravi', 1, '2025-01-28 18:30'), (3, 'Meera', 2, '2025-02-09 09:15'), (4, 'Karthik', 2, '2025-03-15 20:00'), (5, 'Divya', 1, '2025-05-04 12:45'), (6, 'Imran', 1, '2025-06-21 08:20'), (7, 'Sunita', 2, '2025-06-30 16:10'), (8, 'Naveen', 2, '2025-08-17 11:00'), (9, 'Zoya', 1, '2025-09-02 15:30'), (10, 'Kabir', 1, '2025-11-11 19:40'), (11, 'Lata', 2, '2026-01-06 10:10'), (12, 'Mohan', 1, '2026-02-14 13:25'), (13, 'Nisha', 1, '2026-02-20 17:05'), (14, 'Omkar', 2, '2026-03-03 09:50'), (15, 'Pooja', 1, '2026-03-18 21:15');
INSERT INTO categories (category_id, name, parent_id) VALUES (1, 'Dairy', NULL), (2, 'Staples', NULL), (3, 'Snacks', NULL); INSERT INTO products (product_id, category_id, name, price) VALUES (1, 1, 'Toned milk 1 L', 58.00), (2, 1, 'Curd 500 g', 40.00), (3, 1, 'Paneer 200 g', 95.00), (4, 1, 'Table butter 100 g', 55.00), (5, 2, 'Basmati rice 5 kg', 640.00), (6, 2, 'Wheat flour 5 kg', 245.00), (7, 2, 'Toor dal 1 kg', 165.00), (8, 2, 'Sugar 1 kg', 48.00), (9, 3, 'Salted peanuts 200 g', 70.00), (10, 3, 'Banana chips 150 g', 85.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', 2, NULL, 'manager', 50000.00), (7, 'Bhavna', 2, 6, 'picker', 51000.00), (8, 'Chetan', 2, 6, 'rider', 20000.00), (9, 'Deepa', 1, 1, 'rider', 23000.00), (10, 'Eshan', 3, 4, 'picker', 22000.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, 1, '2026-03-03 08:30', 'delivered'), (4, 4, 1, '2026-03-03 12:10', 'delivered'), (5, 5, 1, '2026-03-05 19:45', 'delivered'), (6, 6, 1, '2026-03-06 07:50', 'delivered'), (7, 7, 1, '2026-03-06 13:20', 'delivered'), (8, 8, 1, '2026-03-06 20:05', 'cancelled'), (9, 9, 1, '2026-03-07 10:40', 'delivered'), (10, 10, 1, '2026-03-07 21:00', 'delivered'), (11, 1, 2, '2026-03-02 11:30', 'delivered'), (12, 2, 2, '2026-03-03 17:15', 'delivered'), (13, 3, 2, '2026-03-03 19:00', 'delivered'), (14, 4, 2, '2026-03-04 09:25', 'delivered'), (15, 5, 2, '2026-03-04 15:55', 'placed');
Correlated subquery and window function
The question: which products cost more than the average of their own category? The first form uses a correlated subquery. For each product p, the subquery averages the prices of products in the same category, and the outer WHERE compares.
SELECT p.name, p.price FROM products AS p WHERE p.price > (SELECT avg(p2.price) FROM products AS p2 WHERE p2.category_id = p.category_id) ORDER BY p.name;
name | price -------------------+------- Banana chips 150 g | 85.00 Basmati rice 5 kg | 640.00 Paneer 200 g | 95.00 (3 rows)
The second form uses avg(price) OVER (PARTITION BY category_id). The window computes the category average without collapsing the rows, so each product carries its category average beside it. A window function is not allowed in WHERE, so the comparison happens in an outer query.
SELECT name, price, category_avg FROM ( SELECT name, price, round(avg(price) OVER (PARTITION BY category_id), 2) AS category_avg FROM products ) AS p WHERE price > category_avg ORDER BY name;
name | price | category_avg -------------------+--------+------------- Banana chips 150 g | 85.00 | 77.50 Basmati rice 5 kg | 640.00 | 274.50 Paneer 200 g | 95.00 | 62.00 (3 rows)
Both return the same three products. The window form has a visible advantage: the benchmark is a column you can print, so a reader sees why a row qualified. The subquery form states the benchmark as a condition and does not print it. On large tables the window form reads the table once, where a correlated subquery may be run once per row, although PostgreSQL can often plan either well. Use the window form when you want the benchmark in the output.
Trying the comparison directly in WHERE shows the rule:
SELECT name FROM products WHERE price > avg(price) OVER (PARTITION BY category_id);
ERROR 42P20: window functions are not allowed in WHERE
Showing the distance from the benchmark
Often the question is not only "above" or "below" but by how much. Put the window in the select list, name it once with a WINDOW clause, and compute the percentage difference. A WINDOW clause is a name for a window definition that several functions share.
SELECT c.name AS category, p.name, p.price, round(avg(p.price) OVER w, 2) AS category_avg, round(100 * (p.price - avg(p.price) OVER w) / avg(p.price) OVER w, 1) AS pct_vs_avg FROM products AS p JOIN categories AS c ON c.category_id = p.category_id WINDOW w AS (PARTITION BY p.category_id) ORDER BY c.name, p.price DESC;
category | name | price | category_avg | pct_vs_avg ---------+----------------------+--------+--------------+----------- Dairy | Paneer 200 g | 95.00 | 62.00 | 53.2 Dairy | Toned milk 1 L | 58.00 | 62.00 | -6.5 Dairy | Table butter 100 g | 55.00 | 62.00 | -11.3 Dairy | Curd 500 g | 40.00 | 62.00 | -35.5 Snacks | Banana chips 150 g | 85.00 | 77.50 | 9.7 Snacks | Salted peanuts 200 g | 70.00 | 77.50 | -9.7 Staples | Basmati rice 5 kg | 640.00 | 274.50 | 133.2 Staples | Wheat flour 5 kg | 245.00 | 274.50 | -10.7 Staples | Toor dal 1 kg | 165.00 | 274.50 | -39.9 Staples | Sugar 1 kg | 48.00 | 274.50 | -82.5 (10 rows)
Paneer is 53.2 percent above its category average, and sugar 82.5 percent below its. The percentage is (price - avg) / avg, and multiplying by 100 first or using 100.0 keeps it numeric, as the aggregation chapter showed.
Mind which group is the benchmark. Comparing with the overall average of every product gives a different answer, because the groups differ a lot in price.
SELECT name, price FROM products WHERE price > (SELECT avg(price) FROM products) ORDER BY price DESC;
name | price ------------------+------- Basmati rice 5 kg | 640.00 Wheat flour 5 kg | 245.00 Toor dal 1 kg | 165.00 (3 rows)
Only the staples pass the overall average, because the rice, flour and dal prices pull it up. Dairy and Snacks produce nothing here, because none of their products beats the overall average. The wording of the question decides the benchmark: "dearer than its category" is PARTITION BY category_id, and "dearer than the average product" is an empty OVER ().
Part 2 · Row against the row before it
LAG and LEAD
Trends compare a row with its neighbour: today against yesterday, this reading against the last. lag(x) returns the value of x from the previous row of the window, and lead(x) returns it from the next row. Both work inside the window's order, so the first thing to decide is the order.
The question here is how many orders a store gets each day, and how that changes from one day to the next. A view named daily_orders counts orders per store and day.
CREATE VIEW daily_orders 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 FROM daily_orders ORDER BY store_id, day;
store_id | day | orders ---------+------------+------- 1 | 2026-03-02 | 2 1 | 2026-03-03 | 2 1 | 2026-03-05 | 1 1 | 2026-03-06 | 3 1 | 2026-03-07 | 2 2 | 2026-03-02 | 1 2 | 2026-03-03 | 2 2 | 2026-03-04 | 2 (8 rows)
Store 1 had orders on five days, with nothing on 4 March. Now compare each day with the one before it.
SELECT day::text AS day, orders, lag(orders) OVER (ORDER BY day) AS prev, orders - lag(orders) OVER (ORDER BY day) AS change FROM daily_orders WHERE store_id = 1 ORDER BY day;
day | orders | prev | change -----------+--------+------+------- 2026-03-02 | 2 | NULL | NULL 2026-03-03 | 2 | 2 | 0 2026-03-05 | 1 | 2 | -1 2026-03-06 | 3 | 1 | 2 2026-03-07 | 2 | 3 | -1 (5 rows)
The first row has prev and change as NULL: it has no earlier row. That is the standard edge case of every lag. If NULL is not what you want, lag takes a default as its third argument, lag(orders, 1, 0), and lead works the same way for the last row.
SELECT day::text AS day, orders, lag(orders, 1, 0) OVER (ORDER BY day) AS prev_or_zero, lead(orders) OVER (ORDER BY day) AS next FROM daily_orders WHERE store_id = 1 ORDER BY day;
day | orders | prev_or_zero | next -----------+--------+--------------+----- 2026-03-02 | 2 | 0 | 2 2026-03-03 | 2 | 2 | 1 2026-03-05 | 1 | 2 | 3 2026-03-06 | 3 | 1 | 2 2026-03-07 | 2 | 3 | NULL (5 rows)
Percent change, with two traps
The scene fills the same table cell by cell. Watch what the first row does, and what happens at the gap on 4 March.
Watch for the first row: it has no row above it, so lag has nothing to return
Read it as steps
Daily orders of one store: each change reads the cell above, and the first row has nothing above it.
A percent change is the change divided by the previous value. Two traps hide in that division. The first is integer division: orders is an integer, so 100 * change / prev truncates toward zero, and a drop of one-third shows as -33 where the numeric result is -33.3.
SELECT day::text AS day, orders, 100 * (orders - lag(orders) OVER (ORDER BY day)) / lag(orders) OVER (ORDER BY day) AS pct_integer, round(100.0 * (orders - lag(orders) OVER (ORDER BY day)) / lag(orders) OVER (ORDER BY day), 1) AS pct_numeric FROM daily_orders WHERE store_id = 1 ORDER BY day;
day | orders | pct_integer | pct_numeric -----------+--------+-------------+------------ 2026-03-02 | 2 | NULL | NULL 2026-03-03 | 2 | 0 | 0.0 2026-03-05 | 1 | -50 | -50.0 2026-03-06 | 3 | 200 | 200.0 2026-03-07 | 2 | -33 | -33.3 (5 rows)
The second is a zero in the previous row. A day that follows a day with no orders divides by zero. With nullif(prev, 0) the percentage is NULL, which says "undefined" and does not fail the query.
Gaps and groups
lag looks back one row, not one day. Store 1 has no row for 4 March, so on 5 March lag returns the value of 3 March. Subtracting the dates shows the jump.
SELECT day::text AS day, orders, day - lag(day) OVER (ORDER BY day) AS days_since_prev_row FROM daily_orders WHERE store_id = 1 ORDER BY day;
day | orders | days_since_prev_row -----------+--------+-------------------- 2026-03-02 | 2 | NULL 2026-03-03 | 2 | 1 2026-03-05 | 1 | 2 2026-03-06 | 3 | 1 2026-03-07 | 2 | 1 (5 rows)
Two days between the rows on 3 and 5 March. If a change should be against yesterday and not against the last day with data, build a gap-free calendar first, as the aggregation chapter shows, and take lag over the calendar. Or join the table to itself on day = prev.day + 1.
The second thing to decide is the partition. Without PARTITION BY, the window treats all stores as one sequence, and the first day of store 2 gets compared with the last day of store 1. Compare the two versions.
SELECT store_id, day::text AS day, orders, orders - lag(orders) OVER (ORDER BY store_id, day) AS change FROM daily_orders ORDER BY store_id, day;
store_id | day | orders | change ---------+------------+--------+------- 1 | 2026-03-02 | 2 | NULL 1 | 2026-03-03 | 2 | 0 1 | 2026-03-05 | 1 | -1 1 | 2026-03-06 | 3 | 2 1 | 2026-03-07 | 2 | -1 2 | 2026-03-02 | 1 | -1 2 | 2026-03-03 | 2 | 1 2 | 2026-03-04 | 2 | 0 (8 rows)
The row for store 2 on 2 March shows a change of -1, which compares it with store 1's last day. That number is wrong. With PARTITION BY store_id, each store restarts and its first row is NULL.
SELECT store_id, day::text AS day, orders, orders - lag(orders) OVER (PARTITION BY store_id ORDER BY day) AS change FROM daily_orders ORDER BY store_id, day;
store_id | day | orders | change ---------+------------+--------+------- 1 | 2026-03-02 | 2 | NULL 1 | 2026-03-03 | 2 | 0 1 | 2026-03-05 | 1 | -1 1 | 2026-03-06 | 3 | 2 1 | 2026-03-07 | 2 | -1 2 | 2026-03-02 | 1 | NULL 2 | 2026-03-03 | 2 | 1 2 | 2026-03-04 | 2 | 0 (8 rows)
Part 3 · Row against a paired row
Self-joins
Some comparisons are against a specific other row in the same table. An employee against their manager. A customer against another in the same city. The row to compare with is not the previous one or a group, but a partner chosen by a rule. When both rows are in one table, you join the table to itself, giving it two aliases that act as two copies.
In the staff table, manager_id points to another row of the same table. A self-join pairs each employee e with the row m of their manager. The question "who earns more than their manager?" is then an ordinary comparison between two columns of the joined row.
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary FROM staff AS e JOIN staff AS m ON m.staff_id = e.manager_id WHERE e.salary > m.salary ORDER BY e.name;
employee | salary | manager | manager_salary ---------+----------+---------+--------------- Bhavna | 51000.00 | Ajay | 50000.00 (1 row)
Only Bhavna earns more than her manager, Ajay: 51,000 against 50,000. The full list shows how far each is from the manager.
SELECT e.name AS employee, m.name AS manager, e.salary - m.salary AS difference FROM staff AS e JOIN staff AS m ON m.staff_id = e.manager_id ORDER BY e.staff_id;
employee | manager | difference ---------+---------+----------- Rohit | Lakshmi | -31000.00 Farah | Lakshmi | -29000.00 Tanvi | Gopal | -26000.00 Bhavna | Ajay | 1000.00 Chetan | Ajay | -30000.00 Deepa | Lakshmi | -29000.00 Eshan | Gopal | -26000.00 (7 rows)
Seven rows for ten staff. The three managers are missing, because their manager_id is NULL and an inner join drops them. That is right for this question, since a manager at the top has nobody to compare with. If you need them in the output, use a LEFT JOIN and accept NULLs on the manager side, as the next query does for store 2, where Ajay shows a NULL manager.
SELECT e.name AS employee, m.name AS manager FROM staff AS e LEFT JOIN staff AS m ON m.staff_id = e.manager_id WHERE e.store_id = 2 ORDER BY e.staff_id;
employee | manager
---------+--------
Ajay | NULL
Bhavna | Ajay
Chetan | Ajay
(3 rows)Pairs of rows, and mirrored copies
Another kind of pairing has no hierarchy: find two staff with the same salary. The self-join matches each row with every other row that has the same salary. The condition b.staff_id <> a.staff_id stops a row from matching itself, but see what comes back.
SELECT a.name AS first, b.name AS second, a.salary FROM staff AS a JOIN staff AS b ON b.salary = a.salary AND b.staff_id <> a.staff_id ORDER BY a.salary, a.name;
first | second | salary ------+--------+--------- Eshan | Tanvi | 22000.00 Tanvi | Eshan | 22000.00 Deepa | Farah | 23000.00 Farah | Deepa | 23000.00 (4 rows)
Each pair appears twice, once as (Farah, Deepa) and once as (Deepa, Farah). The two pairs are mirrored copies of each other. To keep each pair once, ask for the second id to be larger than the first: b.staff_id > a.staff_id. That condition also removes the self-match, so it replaces the <> test.
SELECT a.name AS first, b.name AS second, a.salary FROM staff AS a JOIN staff AS b ON b.salary = a.salary AND b.staff_id > a.staff_id ORDER BY a.salary, a.name;
first | second | salary ------+--------+--------- Tanvi | Eshan | 22000.00 Farah | Deepa | 23000.00 (2 rows)
The count of ordered pairs and unordered pairs in the whole table shows the effect in numbers: ten people form 90 ordered pairs of two different people, and exactly half of them, 45, remain once the mirrored copies are removed.
SELECT count(*) AS ordered_pairs, count(*) FILTER (WHERE a.staff_id < b.staff_id) AS unordered_pairs FROM staff AS a CROSS JOIN staff AS b WHERE a.staff_id <> b.staff_id;
ordered_pairs | unordered_pairs --------------+---------------- 90 | 45 (1 row)
A group of tied rows grows quickly. Two rows with the same salary make one pair, three make three pairs, and four make six, which is k times (k minus 1) divided by 2 for k rows. If the question is only whether duplicates exist, GROUP BY salary HAVING count(*) > 1 answers it without building the pairs, as the filtering chapter shows. Build the pairs only when you need to see both members. Add the cheapest selective condition you have, a shared store or a shared date, to the ON clause, so that the database does not have to consider every possible pair.
Pairs with extra conditions
Conditions on either side of the pair go in the ON or the WHERE, as for any join. Which pairs of riders work in the same store? Join on the store, keep the larger id on the right, and filter both roles.
SELECT a.name AS first, b.name AS second, a.store_id FROM staff AS a JOIN staff AS b ON b.store_id = a.store_id AND b.staff_id > a.staff_id WHERE a.role = 'rider' AND b.role = 'rider' ORDER BY a.store_id, a.name;
first | second | store_id ------+--------+--------- Farah | Deepa | 1 (1 row)
Farah and Deepa, both riders in Kothrud. Chetan is the only rider in Viman Nagar, and nobody is a rider in Madhapur, so no other pair exists.
Both pair conditions above compare a row with one partner. The next page compares a row with the rest of its group.
Against the rest of the group
A self-join can also compare a row with the rest of its group while leaving the row itself out. The question is who earns more than the average of the others in the same store. The condition b.staff_id <> a.staff_id removes the row itself from its own benchmark, and the average over b is then grouped back to one row per a. Grouping by a.staff_id is enough to allow a.name and a.salary in the select list, because the primary key determines them.
SELECT a.name, a.salary, round(avg(b.salary), 0) AS others_avg FROM staff AS a JOIN staff AS b ON b.store_id = a.store_id AND b.staff_id <> a.staff_id GROUP BY a.staff_id, a.name, a.salary HAVING a.salary > avg(b.salary) ORDER BY a.name;
name | salary | others_avg --------+----------+----------- Ajay | 50000.00 | 35500 Bhavna | 51000.00 | 35000 Gopal | 48000.00 | 22000 Lakshmi | 52000.00 | 22333 (4 rows)
Four people pass: the three managers and Bhavna, whose manager earns less than she does. The window average of lesson 1 includes the row itself in its benchmark, and this form does not, which matters most in small groups. A store with a single employee produces no row at all here, because an inner join finds no other person to compare with. A LEFT JOIN would keep that employee with a NULL average, and the comparison with NULL is not true, so the row would still be filtered out.
NULL keys and the cost of a self-join
Joins on a column that can be NULL have one more edge. A NULL never equals a NULL, so two rows with a missing salary are not paired by =. IS NOT DISTINCT FROM treats two NULLs as equal and pairs them. The check below crosses two lists that each hold a 1 and a NULL: the equality counts one pair, and the NULL-safe form counts two.
SELECT count(*) FILTER (WHERE a.x = b.x) AS with_equals, count(*) FILTER (WHERE a.x IS NOT DISTINCT FROM b.x) AS with_not_distinct FROM (VALUES (1), (NULL)) AS a (x) CROSS JOIN (VALUES (1), (NULL)) AS b (x);
with_equals | with_not_distinct ------------+------------------ 1 | 2 (1 row)
Decide which one the question wants. For a duplicate search, two missing values usually should match. For a comparison of amounts, they usually should not.
A self-join over a large table with a loose condition grows fast: the output has about n squared over two rows when the condition matches every pair. Give the join a selective equality, such as the same store or the same date, and let an index on that column help. When the comparison is with the neighbour in an order, lag and lead do it without a join, and when it is with a group, a window aggregate does.
Why does a self-join on salary return each pair twice?
- The pair (a, b) matches in both directions, so (Farah, Deepa) and (Deepa, Farah) both appear.
- Requiring
b.staff_id > a.staff_idkeeps one direction and also removes self-matches.
Why are the three managers missing from the manager comparison?
- Their
manager_idis NULL, and an inner join does not match NULL. - Use a
LEFT JOINto keep them, with NULL on the manager side.
How many pairs of different people can you form from ten rows, counting each pair once?
- 45, which is 10 times 9 divided by 2.
Part 4 · Period against period
Months as a series
Business reports compare a period with the one before it, month over month, and with the same period a year ago, year over year. A period report needs one row per period, so the first step is the gap-free calendar again. Here the measure is the number of customer signups per month, from January 2025 to March 2026.
CREATE VIEW monthly AS SELECT m::date AS month, count(c.customer_id) AS signups FROM generate_series('2025-01-01'::date, '2026-03-01'::date, interval '1 month') AS m LEFT JOIN customers AS c ON date_trunc('month', c.signed_up_at)::date = m::date GROUP BY m;
SELECT month::text AS month, signups FROM monthly ORDER BY month;
month | signups -----------+-------- 2025-01-01 | 2 2025-02-01 | 1 2025-03-01 | 1 2025-04-01 | 0 2025-05-01 | 1 2025-06-01 | 2 2025-07-01 | 0 2025-08-01 | 1 2025-09-01 | 1 2025-10-01 | 0 2025-11-01 | 1 2025-12-01 | 0 2026-01-01 | 1 2026-02-01 | 2 2026-03-01 | 2 (15 rows)
Fifteen months, with zeros in April, July, October and December 2025, which have no signups. Without the calendar, those months would not exist and every comparison across them would be against the wrong month.
Month over month
Month over month compares each month with the one before. Because the series has one row per month, lag reaches back exactly one month.
SELECT month, signups, vs_last_month FROM ( SELECT month::text AS month, signups, signups - lag(signups) OVER (ORDER BY month) AS vs_last_month FROM monthly ) AS t WHERE month >= '2025-11-01' ORDER BY month;
month | signups | vs_last_month -----------+---------+-------------- 2025-11-01 | 1 | 1 2025-12-01 | 0 | -1 2026-01-01 | 1 | 1 2026-02-01 | 2 | 1 2026-03-01 | 2 | 0 (5 rows)
December 2025 had no signups, a drop of one from November, and January 2026 recovers by one. Notice where the filter is. The window runs over the whole series in the inner query, and the filter on month is outside it. That order matters. If the WHERE is in the same query as the window, it runs first, rows are removed, and lag reaches across the hole.
SELECT month::text AS month, signups, signups - lag(signups) OVER (ORDER BY month) AS vs_last_month FROM monthly WHERE signups > 0 AND month >= '2025-08-01' AND month < '2026-01-01' ORDER BY month;
month | signups | vs_last_month -----------+---------+-------------- 2025-08-01 | 1 | NULL 2025-09-01 | 1 | 0 2025-11-01 | 1 | 0 (3 rows)
This query kept only months with signups, so the window saw August, September and November and nothing else. November shows a change of 0, because its previous row is September with 1 signup, while the real change from October, which had none, is +1. The first row is NULL because the earlier months were already filtered out. Compute window functions first and filter in an outer query.
Year over year, and date arithmetic
Year over year compares a month with the same month twelve months earlier. On a gap-free monthly series, lag(signups, 12) does it: the second argument is the offset in rows. The newest four months show it.
SELECT month::text AS month, signups, lag(signups, 12) OVER (ORDER BY month) AS same_month_last_year FROM monthly ORDER BY month DESC LIMIT 4;
month | signups | same_month_last_year -----------+---------+--------------------- 2026-03-01 | 2 | 1 2026-02-01 | 2 | 1 2026-01-01 | 1 | 2 2025-12-01 | 0 | NULL (4 rows)
March 2026 had 2 signups against 1 in March 2025. December 2025 shows NULL, because the series starts in January 2025, so no row exists twelve places before it. That works only while the calendar has exactly one row per month. A safer form joins the series to itself and states the date arithmetic: the previous year's row is the one whose month equals this month minus one year.
SELECT cur.month::text AS month, cur.signups, prev.signups AS same_month_last_year, cur.signups - prev.signups AS change FROM monthly AS cur LEFT JOIN monthly AS prev ON prev.month = (cur.month - interval '1 year')::date WHERE cur.month >= '2026-01-01' ORDER BY cur.month;
month | signups | same_month_last_year | change -----------+---------+----------------------+------- 2026-01-01 | 1 | 2 | -1 2026-02-01 | 2 | 1 | 1 2026-03-01 | 2 | 1 | 1 (3 rows)
January 2026 had 1 signup against 2 a year earlier, so the change is -1. This join form keeps working if months are missing from the series, because it matches on the date, and not on the position.
Date arithmetic follows the calendar, not a fixed number of days. Subtracting a month from 31 March gives 28 February, and adding a month to 31 January also gives 28 February. A leap day plus a year lands on 28 February of the next year. Dates at the end of a month clamp to the last valid day, which is the behaviour you want for monthly reports.
SELECT ('2026-03-31'::date - interval '1 month')::date::text AS minus_1m, ('2026-01-31'::date + interval '1 month')::date::text AS plus_1m, ('2024-02-29'::date + interval '1 year')::date::text AS plus_1y;
minus_1m | plus_1m | plus_1y -----------+------------+----------- 2026-02-28 | 2026-02-28 | 2025-02-28 (1 row)
Cautions for period comparisons
Two cautions apply to every period comparison. First, the latest period is usually incomplete. If today is 18 March, comparing March so far with a full February says the business is shrinking, which is a mistake in the question and not in the data. Either leave the current month out, or compare the same span of days in both periods. The query below does the second. It counts signups in the first 18 days of each month next to the whole month.
SELECT date_trunc('month', signed_up_at)::date::text AS month, count(*) FILTER (WHERE extract(day FROM signed_up_at) <= 18) AS first_18_days, count(*) AS whole_month FROM customers WHERE signed_up_at >= '2026-02-01' GROUP BY date_trunc('month', signed_up_at) ORDER BY month;
month | first_18_days | whole_month -----------+---------------+------------ 2026-02-01 | 1 | 2 2026-03-01 | 2 | 2 (2 rows)
Against the whole of February, March looks flat: 2 and 2. Against the first 18 days of February, March has doubled: 2 and 1. The second comparison is the fair one, because both months have had the same number of days to collect signups. The day limit uses the session time zone, as the earlier date work did.
Second, percentage change is unstable on small bases, and it is undefined when the previous value is 0. The next query shows what the monthly series does when the percentage is guarded with nullif. The drop from 1 to 0 is minus 100 percent, and the move from 0 to 1 has no percentage at all.
SELECT month, signups, pct_change FROM ( SELECT month::text AS month, signups, round(100.0 * (signups - lag(signups) OVER (ORDER BY month)) / nullif(lag(signups) OVER (ORDER BY month), 0), 1) AS pct_change FROM monthly ) AS t WHERE month >= '2025-09-01' ORDER BY month;
month | signups | pct_change -----------+---------+----------- 2025-09-01 | 1 | 0.0 2025-10-01 | 0 | -100.0 2025-11-01 | 1 | NULL 2025-12-01 | 0 | -100.0 2026-01-01 | 1 | NULL 2026-02-01 | 2 | 100.0 2026-03-01 | 2 | 0.0 (7 rows)
A move from 1 signup to 2 is plus 100 percent, which sounds dramatic and means one more person. Show the counts beside the percentage so that the reader can judge. Both cautions are about the meaning of the question, which no window function can check for you.
Part 5 · Against the extremes
The Nth highest value
"The second highest salary" and "the third highest" ask for a comparison against the extremes of a ranking. The challenge is again ties. The ten staff have salaries in which 23,000 and 22,000 each appear twice. The ranks tell the story.
SELECT name, salary, rank() OVER (ORDER BY salary DESC) AS rnk, dense_rank() OVER (ORDER BY salary DESC) AS dense FROM staff ORDER BY salary DESC, name;
name | salary | rnk | dense --------+----------+-----+------ Lakshmi | 52000.00 | 1 | 1 Bhavna | 51000.00 | 2 | 2 Ajay | 50000.00 | 3 | 3 Gopal | 48000.00 | 4 | 4 Deepa | 23000.00 | 5 | 5 Farah | 23000.00 | 5 | 5 Eshan | 22000.00 | 7 | 6 Tanvi | 22000.00 | 7 | 6 Rohit | 21000.00 | 9 | 7 Chetan | 20000.00 | 10 | 8 (10 rows)
rank gives both 23,000 earners rank 5 and skips to 7 for the next. dense_rank gives them 5 and then 6, with no gap. "The third highest salary" means the third distinct value, so dense_rank is the right function: it picks 50,000, which belongs to Ajay.
SELECT DISTINCT salary FROM ( SELECT salary, dense_rank() OVER (ORDER BY salary DESC) AS rnk FROM staff ) AS r WHERE rnk = 3;
salary -------- 50000.00 (1 row)
The version that does not need a window function takes distinct salaries in descending order and skips two. It gives the same value here.
SELECT DISTINCT salary FROM staff ORDER BY salary DESC OFFSET 2 LIMIT 1;
salary -------- 50000.00 (1 row)
The OFFSET form is short, but it returns nothing if there is no third salary, and it gives only the value, not the people who earn it. The dense_rank form can return the people as well, because it keeps the rows. Pick by what the question wants back.
FIRST_VALUE and LAST_VALUE
first_value(x) returns x from the first row of the window frame, and last_value(x) from the last. They compare each row with the extreme of its group. Here is each employee beside the top earner of their store.
SELECT name, store_id, salary, first_value(name) OVER (PARTITION BY store_id ORDER BY salary DESC) AS top_earner FROM staff ORDER BY store_id, salary DESC, name;
name | store_id | salary | top_earner --------+----------+----------+----------- Lakshmi | 1 | 52000.00 | Lakshmi Deepa | 1 | 23000.00 | Lakshmi Farah | 1 | 23000.00 | Lakshmi Rohit | 1 | 21000.00 | Lakshmi Bhavna | 2 | 51000.00 | Bhavna Ajay | 2 | 50000.00 | Bhavna Chetan | 2 | 20000.00 | Bhavna Gopal | 3 | 48000.00 | Gopal Eshan | 3 | 22000.00 | Gopal Tanvi | 3 | 22000.00 | Gopal (10 rows)
If two people tie for the top of a store, first_value returns one of them, and which one is not defined unless the ORDER BY has a tiebreaker. Put a unique column such as name or staff_id last in the ORDER BY of the window whenever the answer must be repeatable.
The same difference can be a number: how far each salary is below the top in the store. Store 2 has three people, and Chetan earns 31,000 less than Bhavna.
SELECT name, salary, salary - first_value(salary) OVER (ORDER BY salary DESC) AS gap_to_top FROM staff WHERE store_id = 2 ORDER BY salary DESC;
name | salary | gap_to_top -------+----------+----------- Bhavna | 51000.00 | 0.00 Ajay | 50000.00 | -1000.00 Chetan | 20000.00 | -31000.00 (3 rows)
last_value surprises almost everyone once. The window is ordered by salary descending, so the last row of the group should be the lowest paid. Look at the result for store 1.
SELECT name, store_id, salary, last_value(name) OVER (PARTITION BY store_id ORDER BY salary DESC) AS lowest_paid FROM staff WHERE store_id = 1 ORDER BY salary DESC, name;
name | store_id | salary | lowest_paid --------+----------+----------+------------ Lakshmi | 1 | 52000.00 | Lakshmi Deepa | 1 | 23000.00 | Deepa Farah | 1 | 23000.00 | Deepa Rohit | 1 | 21000.00 | Rohit (4 rows)
Fixing the frame, ALL and ANY
The cure is to state the frame: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING makes it the whole partition. Now every row of store 1 shows Rohit, who earns 21,000.
SELECT name, store_id, salary, last_value(name) OVER (PARTITION BY store_id ORDER BY salary DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lowest_paid FROM staff WHERE store_id = 1 ORDER BY salary DESC, name;
name | store_id | salary | lowest_paid --------+----------+----------+------------ Lakshmi | 1 | 52000.00 | Rohit Deepa | 1 | 23000.00 | Rohit Farah | 1 | 23000.00 | Rohit Rohit | 1 | 21000.00 | Rohit (4 rows)
first_value did not have the problem, because the frame always starts at the first row. An easier way to get the lowest value is to reverse the ORDER BY and use first_value, which needs no frame.
ALL and ANY compare a value with a whole set. >= ALL (subquery) is true when the value is at least as large as every value in the set, and > ANY (subquery) is true when it is larger than at least one. The first finds the top earner, and the second finds the riders who earn more than at least one picker.
SELECT name, salary FROM staff WHERE salary >= ALL (SELECT salary FROM staff) ORDER BY name;
name | salary --------+--------- Lakshmi | 52000.00 (1 row)
SELECT name, salary FROM staff WHERE role = 'rider' AND salary > ANY (SELECT salary FROM staff WHERE role = 'picker') ORDER BY name;
name | salary ------+--------- Deepa | 23000.00 Farah | 23000.00 (2 rows)
Farah and Deepa earn 23,000, more than Rohit at 21,000, so both qualify. ALL has the same NULL problem as NOT IN. If the set contains a NULL, the comparison can never be true: it is false when some value in the set is at least as large, and unknown otherwise. In the run the set holds 1 and NULL, and 5 > ALL is unknown, which a WHERE treats as not true.
SELECT 5 > ALL (SELECT x FROM (VALUES (1), (NULL)) AS v (x)) AS result;
result
------
NULL
(1 row)All chapters · Previous: Filtering Patterns: Existence, Exclusion, Aggregate Filters and Top-N per Group