Top N per group
“The best product of each merchant”, “the latest subscription of each customer”, “the top three in every country”. GROUP BY cannot answer these: MAX gives the best value, not the row it came from. A window function numbers the rows inside each group and keeps them all, so the next step can pick the rows it needs. This often arrives as a follow-up, after the base query already works.
Window functions from zero
Section titled “Window functions from zero”GROUP BY collapses each group into one row. A window function does a calculation over a group too, but every input row stays in the output, with the result next to it. Here each payout of two merchants gets a number inside its merchant and the merchant’s payout count:
SELECT merchant_id, payout_id, channel, amount_usd, paid_at, ROW_NUMBER() OVER (PARTITION BY merchant_id ORDER BY paid_at DESC, payout_id DESC) AS rn, COUNT(*) OVER (PARTITION BY merchant_id) AS payoutsFROM channel_payoutsWHERE merchant_id IN ('mer_01', 'mer_02')ORDER BY merchant_id, rn;| merchant_id | payout_id | channel | amount_usd | paid_at | rn | payouts |
|---|---|---|---|---|---|---|
| mer_01 | po_0007 | north_market | 69.64 | 2026-09-02 09:00:00 | 1 | 14 |
| mer_01 | po_0014 | south_market | 137.62 | 2026-08-15 09:00:00 | 2 | 14 |
| mer_01 | po_0006 | north_market | 97.69 | 2026-08-02 09:00:00 | 3 | 14 |
| mer_02 | po_0026 | south_market | 154.57 | 2026-09-15 09:00:00 | 1 | 13 |
| mer_02 | po_0019 | north_market | 426.77 | 2026-09-02 09:00:00 | 2 | 13 |
| mer_02 | po_0173 | north_market | 363.75 | 2026-08-02 09:00:00 | 3 | 13 |
The query returns all 27 payouts; these are the first three of each merchant. The parts of the window:
OVER (…)turns a function into a window function. An emptyOVER ()means “all rows of the result”.PARTITION BY merchant_idsplits the rows into groups. The numbering starts again at 1 in each group. It is likeGROUP BY, but the rows do not collapse.ORDER BYinsideOVERsets the order in which rows are numbered. It does not sort the output: the lastORDER BYof the query does that.
ROW_NUMBER() needs an ORDER BY to mean anything. COUNT(*) and SUM() work without one and give the group total on every row. That is the base of shares and running totals.
Best or latest per group
Section titled “Best or latest per group”The recipe has three steps:
- If the ranking is on an aggregate (revenue per product), first
GROUP BYdown to one row per (group, item) in a CTE. - In the next step, number the rows:
ROW_NUMBER() OVER (PARTITION BY group ORDER BY …). - Outside, keep
rn = 1, orrn <= Nfor the top N.
The latest payout of every merchant needs no aggregation, so it starts at step 2:
WITH ranked AS ( SELECT merchant_id, channel, period_month, amount_usd, paid_at, ROW_NUMBER() OVER (PARTITION BY merchant_id ORDER BY paid_at DESC, payout_id DESC) AS rn FROM channel_payouts)SELECT merchant_id, channel, period_month, amount_usd, paid_atFROM rankedWHERE rn = 1ORDER BY merchant_id;| merchant_id | channel | period_month | amount_usd | paid_at |
|---|---|---|---|---|
| mer_01 | north_market | 2026-07-01 | 69.64 | 2026-09-02 09:00:00 |
| mer_02 | south_market | 2026-08-01 | 154.57 | 2026-09-15 09:00:00 |
| mer_03 | south_market | 2026-08-01 | 89.20 | 2026-09-15 09:00:00 |
12 rows, one per merchant; the first three are shown. Check one group by hand: mer_01’s row is the one numbered 1 in the table above.
When the ranking is on an aggregate, the shape grows by one CTE. Keep the query that already works and add steps on top of it:
WITH base AS ( -- the query that already works: one row per (merchant, product)),ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY merchant_id ORDER BY net_usd DESC, product_id) AS rn FROM base)SELECT merchant_id, product_id, net_usdFROM rankedWHERE rn = 1;Why the filter needs its own step
Section titled “Why the filter needs its own step”PostgreSQL computes a query in a fixed logical order: FROM and joins, WHERE, GROUP BY, HAVING, then window functions, then the SELECT list, DISTINCT, ORDER BY and LIMIT. Window functions run after WHERE and HAVING, so neither of them can see rn. The filter goes into the next query, which reads the CTE.
The first transaction of every customer. Will this query run?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: customer_id, start_time
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
customer_id— the customerstart_time— start of the period = time of purchase; "started in …" means this column
| customer_id | start_time |
|---|---|
| cus_00001 | 2025-10-12 16:30:29 |
| cus_00002 | 2025-06-25 19:26:50 |
| cus_00003 | 2025-02-27 08:20:21 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT customer_id, start_time FROM transactions WHERE ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY start_time) = 1;
Show answer
No: window functions are not allowed in WHERE. Window functions are computed after WHERE. Compute ROW_NUMBER in a CTE and filter WHERE rn = 1 outside it, or use DISTINCT ON.
This is what PostgreSQL returns for the query as it is:
Show the fix
WITH ranked AS ( SELECT customer_id, start_time, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY start_time) AS rn FROM transactions)SELECT customer_id, start_timeFROM rankedWHERE rn = 1;| customer_id | start_time |
|---|---|
| cus_00001 | 2025-10-12 16:30:29 |
| cus_00002 | 2025-06-25 19:26:50 |
| cus_00003 | 2025-02-27 08:20:21 |
| cus_00004 | 2026-05-28 06:30:16 |
| cus_00005 | 2025-09-03 02:06:32 |
| cus_00006 | 2025-08-23 02:27:14 |
| cus_00007 | 2025-09-06 17:13:13 |
| cus_00008 | 2025-04-11 02:12:24 |
| cus_00009 | 2026-08-22 17:21:33 |
| cus_00010 | 2025-08-29 14:42:03 |
| cus_00011 | 2025-09-02 09:40:14 |
| cus_00012 | 2026-06-03 09:39:20 |
| cus_00013 | 2026-06-26 00:17:05 |
| cus_00014 | 2026-06-02 17:47:12 |
| cus_00015 | 2026-07-19 15:34:17 |
| cus_00016 | 2026-08-20 20:07:00 |
| cus_00017 | 2025-04-16 12:52:37 |
| cus_00018 | 2025-10-01 05:47:46 |
| cus_00019 | 2025-11-09 08:17:11 |
| cus_00020 | 2025-12-06 01:00:17 |
| cus_00021 | 2026-01-30 20:59:34 |
| cus_00022 | 2026-01-08 15:42:11 |
| cus_00023 | 2026-04-22 16:05:05 |
| cus_00024 | 2025-11-14 08:10:44 |
| cus_00025 | 2026-08-13 07:04:45 |
| cus_00026 | 2026-03-12 07:58:03 |
| cus_00027 | 2026-07-27 21:40:47 |
| cus_00028 | 2026-05-02 16:23:11 |
| cus_00029 | 2025-03-21 10:24:10 |
| cus_00030 | 2025-08-08 02:20:18 |
| cus_00031 | 2026-05-04 00:12:52 |
| cus_00032 | 2026-05-15 07:59:20 |
| cus_00033 | 2025-08-05 16:33:18 |
| cus_00034 | 2025-02-01 09:00:11 |
| cus_00035 | 2026-04-22 09:19:46 |
| cus_00036 | 2025-04-21 21:04:09 |
| cus_00037 | 2026-08-30 22:50:13 |
| cus_00038 | 2026-01-15 02:30:38 |
| cus_00039 | 2026-03-22 06:24:46 |
| cus_00040 | 2025-07-06 17:45:04 |
| cus_00041 | 2026-04-04 00:37:40 |
| cus_00042 | 2026-06-28 12:30:56 |
| cus_00043 | 2025-11-20 04:21:10 |
| cus_00044 | 2026-09-04 10:18:13 |
| cus_00045 | 2026-08-11 10:21:08 |
| cus_00046 | 2025-06-05 05:25:55 |
| cus_00047 | 2026-06-20 13:50:56 |
| cus_00048 | 2025-03-18 05:41:57 |
| cus_00049 | 2026-04-10 02:35:29 |
| cus_00050 | 2025-11-08 14:39:17 |
| cus_00051 | 2026-08-13 21:22:35 |
| cus_00052 | 2025-07-05 21:18:40 |
| cus_00053 | 2025-10-23 14:34:48 |
| cus_00054 | 2025-04-06 08:10:51 |
| cus_00055 | 2026-04-29 08:52:26 |
| cus_00056 | 2025-01-03 10:17:52 |
| cus_00057 | 2026-01-31 23:44:21 |
| cus_00058 | 2025-12-03 19:25:42 |
| cus_00059 | 2025-08-29 22:58:47 |
| cus_00060 | 2025-09-08 19:20:21 |
| cus_00061 | 2026-05-25 21:13:55 |
| cus_00062 | 2025-10-22 19:54:03 |
| cus_00063 | 2026-04-13 10:59:59 |
| cus_00064 | 2025-10-30 00:47:55 |
| cus_00065 | 2025-12-27 07:58:25 |
| cus_00066 | 2025-10-30 12:19:56 |
| cus_00067 | 2026-07-25 13:19:02 |
| cus_00068 | 2026-08-22 13:52:21 |
| cus_00069 | 2025-08-15 23:34:49 |
| cus_00070 | 2025-04-29 03:32:19 |
| cus_00071 | 2025-09-07 04:35:05 |
| cus_00072 | 2026-06-10 21:36:52 |
| cus_00073 | 2025-03-04 17:26:21 |
| cus_00074 | 2025-03-09 04:35:40 |
| cus_00075 | 2025-04-12 04:09:56 |
| cus_00076 | 2025-03-10 03:19:17 |
| cus_00077 | 2026-07-30 12:00:07 |
| cus_00078 | 2025-12-25 20:15:10 |
| cus_00079 | 2025-12-14 12:46:49 |
| cus_00080 | 2025-11-16 11:48:37 |
| cus_00081 | 2025-08-09 18:39:14 |
| cus_00082 | 2025-02-16 08:01:43 |
| cus_00083 | 2025-06-29 04:42:12 |
| cus_00084 | 2025-11-17 20:57:45 |
| cus_00085 | 2025-12-14 08:04:01 |
| cus_00086 | 2025-12-26 23:29:59 |
| cus_00087 | 2025-07-01 22:51:46 |
| cus_00088 | 2025-06-04 02:15:09 |
| cus_00089 | 2026-06-21 19:01:57 |
| cus_00090 | 2025-10-18 09:10:29 |
| cus_00091 | 2025-11-14 23:53:10 |
| cus_00092 | 2025-05-11 19:09:55 |
| cus_00093 | 2025-08-20 05:00:30 |
| cus_00094 | 2025-02-08 12:15:40 |
| cus_00095 | 2025-02-14 14:57:32 |
| cus_00096 | 2025-07-18 13:23:33 |
| cus_00097 | 2025-04-04 08:05:02 |
| cus_00098 | 2025-11-23 03:36:27 |
| cus_00099 | 2026-03-10 04:02:53 |
| cus_00100 | 2026-08-12 08:48:31 |
Add a second sort key
Section titled “Add a second sort key”If two payouts of a merchant have the same paid_at, ORDER BY paid_at DESC alone does not decide which one is number 1. PostgreSQL picks one, and the next run may pick the other. A second key, such as payout_id DESC, makes the result the same every time. Say it: “I add a tie-breaker so the result is deterministic.”
DESC applies to one column
Section titled “DESC applies to one column”ORDER BY paid_at DESC, payout_id sorts paid_at from new to old and payout_id from small to large. DESC belongs to the column just before it. If the rule is “then the larger id”, write DESC again: ORDER BY paid_at DESC, payout_id DESC. The same holds for the final ORDER BY.
ROW_NUMBER, RANK and DENSE_RANK
Section titled “ROW_NUMBER, RANK and DENSE_RANK”The three numbering functions differ only on ties. Rank all products by September transactions, test purchases excluded:
WITH per_product AS ( SELECT product_id, COUNT(*) AS transactions FROM transactions WHERE NOT is_test AND start_time >= TIMESTAMP '2026-09-01' AND start_time < TIMESTAMP '2026-10-01' GROUP BY product_id)SELECT product_id, transactions, ROW_NUMBER() OVER (ORDER BY transactions DESC, product_id) AS row_number, RANK() OVER (ORDER BY transactions DESC) AS rank, DENSE_RANK() OVER (ORDER BY transactions DESC) AS dense_rankFROM per_productORDER BY transactions DESC, product_id;| product_id | transactions | row_number | rank | dense_rank |
|---|---|---|---|---|
| prd_13 | 22 | 7 | 7 | 7 |
| prd_01 | 21 | 8 | 8 | 8 |
| prd_05 | 21 | 9 | 8 | 8 |
| prd_07 | 21 | 10 | 8 | 8 |
| prd_11 | 21 | 11 | 8 | 8 |
| prd_18 | 21 | 12 | 8 | 8 |
| prd_03 | 20 | 13 | 13 | 9 |
| prd_14 | 20 | 14 | 13 | 9 |
These are rows 7–14 of 20. Five products have 21 transactions:
ROW_NUMBERgives them 8, 9, 10, 11, 12. The numbers are always unique, so it keeps one row per number.RANKgives all five 8, and the next product gets 13: the places they took are skipped.DENSE_RANKgives all five 8, and the next product gets 9: no gaps.
So “the top 10 products” has two answers. row_number <= 10 returns 10 rows and cuts the group of 21 in the middle. rank <= 10 returns 12 rows. Ask before you choose: “If two rows tie, do you want both of them or just one?”
DISTINCT ON in PostgreSQL
Section titled “DISTINCT ON in PostgreSQL”DISTINCT ON (g) keeps the first row of each group g, in the order of ORDER BY. The latest payout per merchant becomes one short query, with the same 12 rows:
SELECT DISTINCT ON (merchant_id) merchant_id, channel, period_month, amount_usd, paid_atFROM channel_payoutsORDER BY merchant_id, paid_at DESC, payout_id DESC;Three rules. ORDER BY must start with the DISTINCT ON columns, then give the order inside the group. It keeps exactly one row per group, so it cannot do the top 3 or keep ties. And it is PostgreSQL only: in an interview, say that ROW_NUMBER is the portable version.
The latest transaction of every customer with DISTINCT ON; on a tie, the larger transaction_id. What is wrong?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: customer_id, start_time, plan_id
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
customer_id— the customerplan_id— plan, e.g. prd_03.monthlystart_time— start of the period = time of purchase; "started in …" means this column
| customer_id | plan_id | start_time |
|---|---|---|
| cus_00001 | prd_03.annual | 2025-10-12 16:30:29 |
| cus_00002 | prd_08.weekly | 2025-06-25 19:26:50 |
| cus_00003 | prd_19.monthly | 2025-02-27 08:20:21 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT DISTINCT ON (customer_id) customer_id, start_time, plan_id FROM transactions ORDER BY start_time DESC;
Show answer
An error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions. The correct order is ORDER BY customer_id, start_time DESC, transaction_id DESC: first the DISTINCT ON columns, then the order inside the group. The last key settles ties: a customer can have two transactions with the same start_time, and without it PostgreSQL may keep either one. Check’s hidden data has such ties.
This is what PostgreSQL returns for the query as it is:
Show the fix
SELECT DISTINCT ON (customer_id) customer_id, start_time, plan_idFROM transactionsORDER BY customer_id, start_time DESC, transaction_id DESC;| customer_id | start_time | plan_id |
|---|---|---|
| cus_00001 | 2025-10-12 16:30:29 | prd_03.annual |
| cus_00002 | 2025-06-25 19:26:50 | prd_08.weekly |
| cus_00003 | 2026-09-27 08:20:21 | prd_19.monthly |
| cus_00004 | 2026-09-28 06:30:16 | prd_01.monthly |
| cus_00005 | 2026-08-10 02:06:32 | prd_15.monthly |
| cus_00006 | 2025-08-23 02:27:14 | prd_17.annual |
| cus_00007 | 2025-09-06 17:13:13 | prd_20.monthly |
| cus_00008 | 2026-09-11 02:12:24 | prd_13.monthly |
| cus_00009 | 2026-08-22 17:21:33 | prd_16.annual |
| cus_00010 | 2026-09-05 14:42:03 | prd_03.annual |
| cus_00011 | 2025-10-09 09:40:14 | prd_16.monthly |
| cus_00012 | 2026-08-03 09:39:20 | prd_17.monthly |
| cus_00013 | 2026-09-26 00:17:05 | prd_09.monthly |
| cus_00014 | 2026-07-09 17:47:12 | prd_07.monthly |
| cus_00015 | 2026-07-19 15:34:17 | prd_04.weekly |
| cus_00016 | 2026-08-20 20:07:00 | prd_20.weekly |
| cus_00017 | 2025-08-16 12:52:37 | prd_02.monthly |
| cus_00018 | 2025-10-01 05:47:46 | prd_10.annual |
| cus_00019 | 2025-11-16 08:17:11 | prd_07.annual |
| cus_00020 | 2026-01-13 01:00:17 | prd_11.monthly |
| cus_00021 | 2026-01-30 20:59:34 | prd_10.monthly |
| cus_00022 | 2026-09-15 15:42:11 | prd_16.monthly |
| cus_00023 | 2026-06-22 16:05:05 | prd_13.monthly |
| cus_00024 | 2025-11-14 08:10:44 | prd_19.monthly |
| cus_00025 | 2026-08-13 07:04:45 | prd_18.annual |
| cus_00026 | 2026-03-19 07:58:03 | prd_20.weekly |
| cus_00027 | 2026-08-03 21:40:47 | prd_04.annual |
| cus_00028 | 2026-05-02 16:23:11 | prd_13.monthly |
| cus_00029 | 2025-03-21 10:24:10 | prd_16.monthly |
| cus_00030 | 2026-08-08 02:20:18 | prd_03.annual |
| cus_00031 | 2026-05-04 00:12:52 | prd_17.annual |
| cus_00032 | 2026-06-26 07:59:20 | prd_12.weekly |
| cus_00033 | 2025-10-12 16:33:18 | prd_14.monthly |
| cus_00034 | 2025-02-01 09:00:11 | prd_11.monthly |
| cus_00035 | 2026-04-22 09:19:46 | prd_04.weekly |
| cus_00036 | 2025-04-21 21:04:09 | prd_04.annual |
| cus_00037 | 2026-09-06 22:50:13 | prd_12.monthly |
| cus_00038 | 2026-02-15 02:30:38 | prd_17.monthly |
| cus_00039 | 2026-09-22 06:24:46 | prd_19.monthly |
| cus_00040 | 2025-09-13 17:45:04 | prd_12.monthly |
| cus_00041 | 2026-04-04 00:37:40 | prd_16.weekly |
| cus_00042 | 2026-06-28 12:30:56 | prd_09.annual |
| cus_00043 | 2025-11-27 04:21:10 | prd_08.weekly |
| cus_00044 | 2026-09-25 10:18:13 | prd_08.weekly |
| cus_00045 | 2026-09-11 10:21:08 | prd_19.monthly |
| cus_00046 | 2025-06-05 05:25:55 | prd_03.monthly |
| cus_00047 | 2026-07-18 13:50:56 | prd_16.weekly |
| cus_00048 | 2025-03-18 05:41:57 | prd_20.monthly |
| cus_00049 | 2026-09-10 02:35:29 | prd_09.monthly |
| cus_00050 | 2025-12-08 14:39:17 | prd_17.monthly |
| cus_00051 | 2026-09-13 21:22:35 | prd_10.monthly |
| cus_00052 | 2026-07-05 21:18:40 | prd_14.annual |
| cus_00053 | 2026-09-23 14:34:48 | prd_04.monthly |
| cus_00054 | 2026-04-06 08:10:51 | prd_05.annual |
| cus_00055 | 2026-06-29 08:52:26 | prd_09.monthly |
| cus_00056 | 2025-02-14 10:17:52 | prd_12.weekly |
| cus_00057 | 2026-03-14 23:44:21 | prd_12.weekly |
| cus_00058 | 2025-12-03 19:25:42 | prd_08.annual |
| cus_00059 | 2025-12-29 22:58:47 | prd_15.monthly |
| cus_00060 | 2025-09-08 19:20:21 | prd_02.annual |
| cus_00061 | 2026-05-25 21:13:55 | prd_18.annual |
| cus_00062 | 2025-10-22 19:54:03 | prd_08.annual |
| cus_00063 | 2026-04-13 10:59:59 | prd_17.annual |
| cus_00064 | 2025-12-30 00:47:55 | prd_08.monthly |
| cus_00065 | 2026-09-27 07:58:25 | prd_15.monthly |
| cus_00066 | 2025-10-30 12:19:56 | prd_05.annual |
| cus_00067 | 2026-07-25 13:19:02 | prd_07.annual |
| cus_00068 | 2026-08-22 13:52:21 | prd_04.annual |
| cus_00069 | 2025-08-22 23:34:49 | prd_01.annual |
| cus_00070 | 2025-08-05 03:32:19 | prd_04.weekly |
| cus_00071 | 2026-07-07 04:35:05 | prd_19.monthly |
| cus_00072 | 2026-06-17 21:36:52 | prd_04.annual |
| cus_00073 | 2025-03-04 17:26:21 | prd_20.monthly |
| cus_00074 | 2025-03-16 04:35:40 | prd_13.annual |
| cus_00075 | 2025-08-12 04:09:56 | prd_16.monthly |
| cus_00076 | 2025-03-10 03:19:17 | prd_20.monthly |
| cus_00077 | 2026-08-27 12:00:07 | prd_04.weekly |
| cus_00078 | 2026-04-01 20:15:10 | prd_05.monthly |
| cus_00079 | 2026-03-31 11:50:00 | prd_20.weekly |
| cus_00080 | 2026-01-11 10:18:18 | prd_12.monthly |
| cus_00081 | 2025-08-09 18:39:14 | prd_13.monthly |
| cus_00082 | 2025-02-23 08:01:43 | prd_20.annual |
| cus_00083 | 2025-08-06 04:42:12 | prd_09.monthly |
| cus_00084 | 2026-04-17 20:57:45 | prd_02.monthly |
| cus_00085 | 2025-12-14 08:04:01 | prd_12.annual |
| cus_00086 | 2025-12-26 23:29:59 | prd_04.annual |
| cus_00087 | 2026-09-01 22:51:46 | prd_18.monthly |
| cus_00088 | 2026-06-04 02:15:09 | prd_19.annual |
| cus_00089 | 2026-08-21 19:01:57 | prd_02.monthly |
| cus_00090 | 2025-10-18 09:10:29 | prd_10.annual |
| cus_00091 | 2025-11-14 23:53:10 | prd_10.annual |
| cus_00092 | 2025-05-18 19:09:55 | prd_09.annual |
| cus_00093 | 2025-08-20 05:00:30 | prd_07.monthly |
| cus_00094 | 2026-02-08 12:15:40 | prd_15.annual |
| cus_00095 | 2026-02-21 14:57:32 | prd_18.annual |
| cus_00096 | 2026-03-18 13:23:33 | prd_08.monthly |
| cus_00097 | 2026-04-04 08:05:02 | prd_13.annual |
| cus_00098 | 2026-09-23 03:36:27 | prd_12.monthly |
| cus_00099 | 2026-05-10 04:02:53 | prd_05.monthly |
| cus_00100 | 2026-08-12 08:48:31 | prd_15.monthly |
Without a window function
Section titled “Without a window function”Find MAX(paid_at) per merchant in a CTE and join it back to the table on merchant_id and paid_at. This works, but on a tie it returns both rows. Sometimes that is what the task wants, but it is a different answer from ROW_NUMBER.
Can you do it without a window function?
Say your answer out loud first, then open it.
Show the answer
“Yes. I find the maximum per merchant in a CTE and join it back on the merchant and that value. The difference is ties: if two rows share the maximum, the join returns both of them, while ROW_NUMBER keeps one.”
How it comes up in the interview
Section titled “How it comes up in the interview”The base task is a report: “Show net revenue per product for September, with the merchant.” The query groups by merchant and product and returns 20 rows. mer_06 has two products: prd_18 with 313.80 and prd_06 with 239.90. Then the follow-up comes: “Now keep only the best product of each merchant.”
- Ask first: “If two products of one merchant have the same revenue, do you want both, or just one?” Suppose the answer is “just one, the smaller product id”.
- Plan out loud: “I’ll number the products inside each merchant by revenue and keep number one. I can’t filter on a window in the same SELECT, so that’s one more step.”
- Wrap, do not rewrite: the working query becomes the first CTE, without its
ORDER BY. - Check against the base: “Twelve rows, one per merchant. For mer_06 it’s prd_18, which matches the base query: 313.80 against 239.90.”
The first drill below is exactly this step. Top N overall is simpler: ORDER BY net_usd DESC, product_id LIMIT 5, as in Q02 on Revenue reports. The window is needed only when the top is per group.
Practice
Section titled “Practice”For each merchant, the product with the highest net revenue (revenue_usd) in September 2026, test purchases excluded. Ties: smaller product_id. Columns: merchant_id, product_id, net_usd.
Output columns: merchant_id, product_id, net_usdOrder: ORDER BY merchant_id
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
product_id— → products.idstart_time— start of the period = time of purchase; "started in …" means this columnrevenue_usd— revenue net of refunds: 0 if the transaction was refunded (net)is_test— test purchase: exclude it from business numbers
| product_id | start_time | revenue_usd | is_test |
|---|---|---|---|
| prd_01 | 2025-01-05 05:52:57 | 0.00 | false |
| prd_01 | 2025-01-03 05:03:11 | 6.99 | false |
| prd_01 | 2025-01-10 11:02:39 | 6.99 | false |
products — products (20 rows); a merchant can own several
id— key: prd_01 …merchant_id— → merchants.id
| id | merchant_id |
|---|---|
| prd_01 | mer_01 |
| prd_02 | mer_02 |
| prd_03 | mer_03 |
Joins: transactions.product_id = products.id
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
WITH per_product AS ( SELECT p.merchant_id, t.product_id, SUM(t.revenue_usd) AS net_usd FROM transactions t JOIN products p ON p.id = t.product_id WHERE NOT t.is_test AND t.start_time >= TIMESTAMP '2026-09-01' AND t.start_time < TIMESTAMP '2026-10-01' GROUP BY p.merchant_id, t.product_id),ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY merchant_id ORDER BY net_usd DESC, product_id) AS rn FROM per_product)SELECT merchant_id, product_id, net_usdFROM rankedWHERE rn = 1ORDER BY merchant_id;Expected output
| merchant_id | product_id | net_usd |
|---|---|---|
| mer_01 | prd_01 | 264.81 |
| mer_02 | prd_02 | 542.84 |
| mer_03 | prd_03 | 389.82 |
| mer_04 | prd_04 | 155.64 |
| mer_05 | prd_05 | 249.81 |
| mer_06 | prd_18 | 313.80 |
| mer_07 | prd_07 | 225.80 |
| mer_08 | prd_08 | 314.53 |
| mer_09 | prd_09 | 321.86 |
| mer_10 | prd_14 | 223.83 |
| mer_11 | prd_11 | 195.81 |
| mer_12 | prd_15 | 659.76 |
Best per group: aggregate to (merchant, product) first, then ROW_NUMBER inside each merchant, then rn = 1 outside, because a window cannot be filtered in the WHERE of the same SELECT. DESC applies to net_usd only, so the second key product_id sorts ascending and the smaller id wins a tie. The hidden data has a merchant whose two best products tie, so the direction of that key matters.
Rank products by paid transactions in September 2026; equal counts share the same rank. Columns: product_id, transactions, rnk. Only ranks 1–5.
Output columns: product_id, transactions, rnkOrder: ORDER BY rnk, product_id
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
product_id— → products.idchannel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)is_trial— free trial (7 days, price 0)start_time— start of the period = time of purchase; "started in …" means this columnis_test— test purchase: exclude it from business numbers
| product_id | channel | is_trial | start_time | is_test |
|---|---|---|---|---|
| prd_01 | promo | false | 2025-01-05 05:52:57 | false |
| prd_01 | north_market | false | 2025-01-03 05:03:11 | false |
| prd_01 | north_market | false | 2025-01-10 11:02:39 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
WITH c AS ( SELECT product_id, COUNT(*) AS transactions FROM transactions WHERE NOT is_trial AND NOT is_test AND channel <> 'promo' AND start_time >= TIMESTAMP '2026-09-01' AND start_time < TIMESTAMP '2026-10-01' GROUP BY product_id),r AS ( SELECT product_id, transactions, RANK() OVER (ORDER BY transactions DESC) AS rnk FROM c)SELECT product_id, transactions, rnkFROM rWHERE rnk <= 5ORDER BY rnk, product_id;Expected output
| product_id | transactions | rnk |
|---|---|---|
| prd_08 | 49 | 1 |
| prd_04 | 36 | 2 |
| prd_20 | 29 | 3 |
| prd_12 | 28 | 4 |
| prd_15 | 25 | 5 |
| prd_16 | 25 | 5 |
RANK gives equal counts the same place and skips the next places (1, 2, 2, 4). DENSE_RANK does not skip (1, 2, 2, 3). ROW_NUMBER always gives different numbers, so it cannot keep both tied rows. Here prd_15 and prd_16 tie at 25 transactions, so ranks 1–5 give six rows; ROW_NUMBER would drop one of them. This tie is in last place, so DENSE_RANK happens to return the same rows. The hidden data has a tie higher up, and there it does not. The filter rnk <= 5 goes in the outer query, after the window is computed.
Most recent transaction of each customer of prd_03 (test purchases excluded): customer_id, plan_id, start_time. Ties: larger transaction_id.
Output columns: customer_id, plan_id, start_timeOrder: ORDER BY customer_id
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
transaction_id— unique id of the transactioncustomer_id— the customerproduct_id— → products.idplan_id— plan, e.g. prd_03.monthlystart_time— start of the period = time of purchase; "started in …" means this columnis_test— test purchase: exclude it from business numbers
| transaction_id | customer_id | product_id | plan_id | start_time | is_test |
|---|---|---|---|---|---|
| t_000001 | cus_00001 | prd_03 | prd_03.annual | 2025-10-12 16:30:29 | false |
| t_000002 | cus_00002 | prd_08 | prd_08.weekly | 2025-06-25 19:26:50 | false |
| t_000003 | cus_00003 | prd_19 | prd_19.monthly | 2025-02-27 08:20:21 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
WITH ranked AS ( SELECT customer_id, plan_id, start_time, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY start_time DESC, transaction_id DESC) AS rn FROM transactions WHERE product_id = 'prd_03' AND NOT is_test)SELECT customer_id, plan_id, start_timeFROM rankedWHERE rn = 1ORDER BY customer_id;Expected output
| customer_id | plan_id | start_time |
|---|---|---|
| cus_00001 | prd_03.annual | 2025-10-12 16:30:29 |
| cus_00010 | prd_03.annual | 2026-09-05 14:42:03 |
| cus_00030 | prd_03.annual | 2026-08-08 02:20:18 |
| cus_00046 | prd_03.monthly | 2025-06-05 05:25:55 |
| cus_00156 | prd_03.monthly | 2026-05-01 01:04:43 |
| cus_00183 | prd_03.annual | 2026-03-13 19:27:28 |
| cus_00186 | prd_03.annual | 2026-02-23 14:25:49 |
| cus_00187 | prd_03.monthly | 2025-04-10 00:17:36 |
| cus_00222 | prd_03.annual | 2026-04-28 17:48:26 |
| cus_00227 | prd_03.monthly | 2025-11-30 10:03:22 |
| cus_00279 | prd_03.monthly | 2025-12-06 01:22:45 |
| cus_00281 | prd_03.monthly | 2026-01-09 18:18:27 |
| cus_00290 | prd_03.monthly | 2026-09-19 21:04:37 |
| cus_00293 | prd_03.monthly | 2026-06-22 13:09:09 |
| cus_00303 | prd_03.annual | 2026-02-08 13:59:34 |
| cus_00323 | prd_03.annual | 2026-02-11 11:15:49 |
| cus_00338 | prd_03.monthly | 2025-07-07 21:30:20 |
| cus_00350 | prd_03.annual | 2025-10-29 00:30:00 |
| cus_00372 | prd_03.monthly | 2026-09-14 13:39:43 |
| cus_00383 | prd_03.monthly | 2026-08-28 15:03:10 |
| cus_00385 | prd_03.monthly | 2025-04-28 21:33:36 |
| cus_00393 | prd_03.annual | 2026-07-07 21:06:13 |
| cus_00416 | prd_03.monthly | 2026-09-06 07:14:10 |
| cus_00425 | prd_03.monthly | 2026-05-09 08:41:18 |
| cus_00428 | prd_03.monthly | 2026-09-24 05:28:46 |
| cus_00436 | prd_03.annual | 2025-12-10 02:24:25 |
| cus_00487 | prd_03.annual | 2026-04-02 00:44:48 |
| cus_00543 | prd_03.monthly | 2026-04-19 00:52:28 |
| cus_00564 | prd_03.annual | 2026-08-03 15:58:18 |
| cus_00586 | prd_03.monthly | 2026-05-23 23:05:47 |
| cus_00592 | prd_03.annual | 2026-05-27 09:47:41 |
| cus_00595 | prd_03.annual | 2025-03-07 12:27:26 |
| cus_00602 | prd_03.annual | 2026-04-24 06:07:07 |
| cus_00615 | prd_03.monthly | 2026-01-01 23:58:41 |
| cus_00667 | prd_03.annual | 2026-08-16 23:49:09 |
| cus_00672 | prd_03.monthly | 2026-04-24 16:57:43 |
| cus_00723 | prd_03.annual | 2026-09-06 21:07:44 |
| cus_00736 | prd_03.monthly | 2026-09-16 16:04:32 |
| cus_00737 | prd_03.monthly | 2026-09-13 02:50:42 |
| cus_00777 | prd_03.annual | 2026-01-21 00:32:12 |
| cus_00819 | prd_03.annual | 2026-05-21 15:41:45 |
| cus_00828 | prd_03.monthly | 2026-09-16 08:55:18 |
| cus_00832 | prd_03.monthly | 2025-09-24 12:28:04 |
| cus_00841 | prd_03.monthly | 2025-10-10 11:11:57 |
| cus_00869 | prd_03.annual | 2025-04-18 09:05:39 |
| cus_00902 | prd_03.annual | 2026-09-21 00:44:33 |
| cus_00912 | prd_03.annual | 2026-06-15 01:17:58 |
| cus_00927 | prd_03.annual | 2025-11-04 14:19:52 |
| cus_00937 | prd_03.monthly | 2025-12-16 14:22:09 |
| cus_01009 | prd_03.monthly | 2026-09-01 04:31:10 |
| cus_01127 | prd_03.monthly | 2026-09-11 13:13:38 |
| cus_01140 | prd_03.annual | 2026-01-28 22:25:03 |
| cus_01149 | prd_03.annual | 2026-01-27 23:56:43 |
| cus_01161 | prd_03.annual | 2025-02-19 23:03:26 |
| cus_01170 | prd_03.monthly | 2025-07-25 17:32:37 |
| cus_01182 | prd_03.monthly | 2026-09-24 04:31:35 |
| cus_01192 | prd_03.annual | 2026-06-08 18:11:34 |
| cus_01250 | prd_03.annual | 2025-05-25 17:15:45 |
| cus_01269 | prd_03.annual | 2026-01-07 10:15:08 |
| cus_01289 | prd_03.annual | 2025-09-27 08:01:54 |
| cus_01303 | prd_03.annual | 2025-07-30 04:25:41 |
| cus_01316 | prd_03.monthly | 2026-05-11 15:35:33 |
| cus_01327 | prd_03.annual | 2025-05-21 20:43:40 |
| cus_01336 | prd_03.annual | 2026-09-25 13:07:30 |
| cus_01352 | prd_03.monthly | 2025-03-30 01:42:59 |
| cus_01414 | prd_03.annual | 2026-02-27 02:47:12 |
| cus_01424 | prd_03.monthly | 2026-08-29 09:54:26 |
| cus_01438 | prd_03.annual | 2026-05-18 10:36:57 |
| cus_01445 | prd_03.annual | 2026-03-12 17:28:38 |
| cus_01464 | prd_03.annual | 2026-05-09 14:36:58 |
| cus_01476 | prd_03.annual | 2025-11-02 05:17:10 |
| cus_01497 | prd_03.monthly | 2026-05-07 16:54:49 |
| cus_01516 | prd_03.monthly | 2025-12-30 00:21:41 |
| cus_01559 | prd_03.monthly | 2026-09-01 06:53:11 |
| cus_01691 | prd_03.monthly | 2026-05-20 21:32:32 |
| cus_01694 | prd_03.annual | 2026-04-16 23:00:37 |
| cus_01696 | prd_03.annual | 2026-04-24 23:56:35 |
| cus_01700 | prd_03.monthly | 2026-09-11 22:20:23 |
| cus_01733 | prd_03.annual | 2026-07-24 00:47:07 |
| cus_01771 | prd_03.monthly | 2025-06-21 22:37:59 |
| cus_01772 | prd_03.annual | 2026-06-24 02:25:52 |
| cus_01774 | prd_03.annual | 2025-08-13 08:54:08 |
| cus_01796 | prd_03.monthly | 2025-09-27 08:08:53 |
| cus_01809 | prd_03.annual | 2025-08-23 22:31:14 |
| cus_01818 | prd_03.annual | 2026-05-01 00:19:18 |
| cus_01838 | prd_03.monthly | 2026-05-27 20:18:12 |
| cus_01843 | prd_03.annual | 2026-07-31 07:51:24 |
| cus_01849 | prd_03.monthly | 2026-03-22 23:09:59 |
| cus_01883 | prd_03.annual | 2026-01-07 07:07:40 |
| cus_01948 | prd_03.annual | 2026-01-29 20:53:43 |
| cus_01949 | prd_03.annual | 2025-06-04 19:46:22 |
| cus_02021 | prd_03.annual | 2026-04-15 21:07:22 |
| cus_02044 | prd_03.annual | 2026-03-14 21:18:52 |
| cus_02045 | prd_03.annual | 2025-01-02 01:42:24 |
| cus_02049 | prd_03.annual | 2026-05-12 17:30:05 |
| cus_02074 | prd_03.monthly | 2026-03-15 06:29:02 |
| cus_02097 | prd_03.monthly | 2025-08-25 21:24:52 |
| cus_02109 | prd_03.monthly | 2025-02-22 17:04:30 |
| cus_02168 | prd_03.annual | 2026-04-14 12:07:16 |
| cus_02170 | prd_03.annual | 2025-11-16 07:47:52 |
The latest row per group: ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY start_time DESC, transaction_id DESC), and rn = 1 outside. Both keys need DESC, because the rule is “the larger id”. In PostgreSQL the same is shorter: SELECT DISTINCT ON (customer_id) … ORDER BY customer_id, start_time DESC, transaction_id DESC.
Further reading
Section titled “Further reading”- Window functions tutorial —
OVER,PARTITION BYandORDER BYwith short examples. - Window functions —
ROW_NUMBER,RANK,DENSE_RANKand the rest of the list. - Window function processing — why windows run after
WHERE,GROUP BYandHAVING. - DISTINCT ON — the rule about the leading
ORDER BYcolumns.
Related topics
Section titled “Related topics”- Subqueries and CTE — the named steps that hold the base query and the numbering.
- Grouping and counting — the aggregation that comes before the ranking.
- Shares and running totals — the same
OVER, withSUMinstead of a number. - Duplicates and idempotency — the first copy of each event, with the same
ROW_NUMBER. - Subscriptions over time — Q07, the current status of every customer.
- Sorting and top-k — the same task in Python, with sort keys and
heapq.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.