Skip to content

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.

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 payouts
FROM channel_payouts
WHERE merchant_id IN ('mer_01', 'mer_02')
ORDER BY merchant_id, rn;
merchant_idpayout_idchannelamount_usdpaid_atrnpayouts
mer_01po_0007north_market69.642026-09-02 09:00:00114
mer_01po_0014south_market137.622026-08-15 09:00:00214
mer_01po_0006north_market97.692026-08-02 09:00:00314
mer_02po_0026south_market154.572026-09-15 09:00:00113
mer_02po_0019north_market426.772026-09-02 09:00:00213
mer_02po_0173north_market363.752026-08-02 09:00:00313

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 empty OVER () means “all rows of the result”.
  • PARTITION BY merchant_id splits the rows into groups. The numbering starts again at 1 in each group. It is like GROUP BY, but the rows do not collapse.
  • ORDER BY inside OVER sets the order in which rows are numbered. It does not sort the output: the last ORDER BY of 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.

The recipe has three steps:

  1. If the ranking is on an aggregate (revenue per product), first GROUP BY down to one row per (group, item) in a CTE.
  2. In the next step, number the rows: ROW_NUMBER() OVER (PARTITION BY group ORDER BY …).
  3. Outside, keep rn = 1, or rn <= N for 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_at
FROM ranked
WHERE rn = 1
ORDER BY merchant_id;
merchant_idchannelperiod_monthamount_usdpaid_at
mer_01north_market2026-07-0169.642026-09-02 09:00:00
mer_02south_market2026-08-01154.572026-09-15 09:00:00
mer_03south_market2026-08-0189.202026-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_usd
FROM ranked
WHERE rn = 1;

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.

SQLTrap: what will it return?core

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 customer
  • start_time — start of the period = time of purchase; "started in …" means this column
customer_idstart_time
cus_000012025-10-12 16:30:29
cus_000022025-06-25 19:26:50
cus_000032025-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:

Error
window functions are not allowed in WHERE
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_time
FROM ranked
WHERE rn = 1;
customer_idstart_time
cus_000012025-10-12 16:30:29
cus_000022025-06-25 19:26:50
cus_000032025-02-27 08:20:21
cus_000042026-05-28 06:30:16
cus_000052025-09-03 02:06:32
cus_000062025-08-23 02:27:14
cus_000072025-09-06 17:13:13
cus_000082025-04-11 02:12:24
cus_000092026-08-22 17:21:33
cus_000102025-08-29 14:42:03
cus_000112025-09-02 09:40:14
cus_000122026-06-03 09:39:20
cus_000132026-06-26 00:17:05
cus_000142026-06-02 17:47:12
cus_000152026-07-19 15:34:17
cus_000162026-08-20 20:07:00
cus_000172025-04-16 12:52:37
cus_000182025-10-01 05:47:46
cus_000192025-11-09 08:17:11
cus_000202025-12-06 01:00:17
cus_000212026-01-30 20:59:34
cus_000222026-01-08 15:42:11
cus_000232026-04-22 16:05:05
cus_000242025-11-14 08:10:44
cus_000252026-08-13 07:04:45
cus_000262026-03-12 07:58:03
cus_000272026-07-27 21:40:47
cus_000282026-05-02 16:23:11
cus_000292025-03-21 10:24:10
cus_000302025-08-08 02:20:18
cus_000312026-05-04 00:12:52
cus_000322026-05-15 07:59:20
cus_000332025-08-05 16:33:18
cus_000342025-02-01 09:00:11
cus_000352026-04-22 09:19:46
cus_000362025-04-21 21:04:09
cus_000372026-08-30 22:50:13
cus_000382026-01-15 02:30:38
cus_000392026-03-22 06:24:46
cus_000402025-07-06 17:45:04
cus_000412026-04-04 00:37:40
cus_000422026-06-28 12:30:56
cus_000432025-11-20 04:21:10
cus_000442026-09-04 10:18:13
cus_000452026-08-11 10:21:08
cus_000462025-06-05 05:25:55
cus_000472026-06-20 13:50:56
cus_000482025-03-18 05:41:57
cus_000492026-04-10 02:35:29
cus_000502025-11-08 14:39:17
cus_000512026-08-13 21:22:35
cus_000522025-07-05 21:18:40
cus_000532025-10-23 14:34:48
cus_000542025-04-06 08:10:51
cus_000552026-04-29 08:52:26
cus_000562025-01-03 10:17:52
cus_000572026-01-31 23:44:21
cus_000582025-12-03 19:25:42
cus_000592025-08-29 22:58:47
cus_000602025-09-08 19:20:21
cus_000612026-05-25 21:13:55
cus_000622025-10-22 19:54:03
cus_000632026-04-13 10:59:59
cus_000642025-10-30 00:47:55
cus_000652025-12-27 07:58:25
cus_000662025-10-30 12:19:56
cus_000672026-07-25 13:19:02
cus_000682026-08-22 13:52:21
cus_000692025-08-15 23:34:49
cus_000702025-04-29 03:32:19
cus_000712025-09-07 04:35:05
cus_000722026-06-10 21:36:52
cus_000732025-03-04 17:26:21
cus_000742025-03-09 04:35:40
cus_000752025-04-12 04:09:56
cus_000762025-03-10 03:19:17
cus_000772026-07-30 12:00:07
cus_000782025-12-25 20:15:10
cus_000792025-12-14 12:46:49
cus_000802025-11-16 11:48:37
cus_000812025-08-09 18:39:14
cus_000822025-02-16 08:01:43
cus_000832025-06-29 04:42:12
cus_000842025-11-17 20:57:45
cus_000852025-12-14 08:04:01
cus_000862025-12-26 23:29:59
cus_000872025-07-01 22:51:46
cus_000882025-06-04 02:15:09
cus_000892026-06-21 19:01:57
cus_000902025-10-18 09:10:29
cus_000912025-11-14 23:53:10
cus_000922025-05-11 19:09:55
cus_000932025-08-20 05:00:30
cus_000942025-02-08 12:15:40
cus_000952025-02-14 14:57:32
cus_000962025-07-18 13:23:33
cus_000972025-04-04 08:05:02
cus_000982025-11-23 03:36:27
cus_000992026-03-10 04:02:53
cus_001002026-08-12 08:48:31
2600 rows (first 100 shown)

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.”

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.

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_rank
FROM per_product
ORDER BY transactions DESC, product_id;
product_idtransactionsrow_numberrankdense_rank
prd_1322777
prd_0121888
prd_0521988
prd_07211088
prd_11211188
prd_18211288
prd_032013139
prd_142014139

These are rows 7–14 of 20. Five products have 21 transactions:

  • ROW_NUMBER gives them 8, 9, 10, 11, 12. The numbers are always unique, so it keeps one row per number.
  • RANK gives all five 8, and the next product gets 13: the places they took are skipped.
  • DENSE_RANK gives 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 (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_at
FROM channel_payouts
ORDER 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.

SQLTrap: what will it return?

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 customer
  • plan_id — plan, e.g. prd_03.monthly
  • start_time — start of the period = time of purchase; "started in …" means this column
customer_idplan_idstart_time
cus_00001prd_03.annual2025-10-12 16:30:29
cus_00002prd_08.weekly2025-06-25 19:26:50
cus_00003prd_19.monthly2025-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:

Error
SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Show the fix
SELECT DISTINCT ON (customer_id) customer_id, start_time, plan_id
FROM transactions
ORDER BY customer_id, start_time DESC, transaction_id DESC;
customer_idstart_timeplan_id
cus_000012025-10-12 16:30:29prd_03.annual
cus_000022025-06-25 19:26:50prd_08.weekly
cus_000032026-09-27 08:20:21prd_19.monthly
cus_000042026-09-28 06:30:16prd_01.monthly
cus_000052026-08-10 02:06:32prd_15.monthly
cus_000062025-08-23 02:27:14prd_17.annual
cus_000072025-09-06 17:13:13prd_20.monthly
cus_000082026-09-11 02:12:24prd_13.monthly
cus_000092026-08-22 17:21:33prd_16.annual
cus_000102026-09-05 14:42:03prd_03.annual
cus_000112025-10-09 09:40:14prd_16.monthly
cus_000122026-08-03 09:39:20prd_17.monthly
cus_000132026-09-26 00:17:05prd_09.monthly
cus_000142026-07-09 17:47:12prd_07.monthly
cus_000152026-07-19 15:34:17prd_04.weekly
cus_000162026-08-20 20:07:00prd_20.weekly
cus_000172025-08-16 12:52:37prd_02.monthly
cus_000182025-10-01 05:47:46prd_10.annual
cus_000192025-11-16 08:17:11prd_07.annual
cus_000202026-01-13 01:00:17prd_11.monthly
cus_000212026-01-30 20:59:34prd_10.monthly
cus_000222026-09-15 15:42:11prd_16.monthly
cus_000232026-06-22 16:05:05prd_13.monthly
cus_000242025-11-14 08:10:44prd_19.monthly
cus_000252026-08-13 07:04:45prd_18.annual
cus_000262026-03-19 07:58:03prd_20.weekly
cus_000272026-08-03 21:40:47prd_04.annual
cus_000282026-05-02 16:23:11prd_13.monthly
cus_000292025-03-21 10:24:10prd_16.monthly
cus_000302026-08-08 02:20:18prd_03.annual
cus_000312026-05-04 00:12:52prd_17.annual
cus_000322026-06-26 07:59:20prd_12.weekly
cus_000332025-10-12 16:33:18prd_14.monthly
cus_000342025-02-01 09:00:11prd_11.monthly
cus_000352026-04-22 09:19:46prd_04.weekly
cus_000362025-04-21 21:04:09prd_04.annual
cus_000372026-09-06 22:50:13prd_12.monthly
cus_000382026-02-15 02:30:38prd_17.monthly
cus_000392026-09-22 06:24:46prd_19.monthly
cus_000402025-09-13 17:45:04prd_12.monthly
cus_000412026-04-04 00:37:40prd_16.weekly
cus_000422026-06-28 12:30:56prd_09.annual
cus_000432025-11-27 04:21:10prd_08.weekly
cus_000442026-09-25 10:18:13prd_08.weekly
cus_000452026-09-11 10:21:08prd_19.monthly
cus_000462025-06-05 05:25:55prd_03.monthly
cus_000472026-07-18 13:50:56prd_16.weekly
cus_000482025-03-18 05:41:57prd_20.monthly
cus_000492026-09-10 02:35:29prd_09.monthly
cus_000502025-12-08 14:39:17prd_17.monthly
cus_000512026-09-13 21:22:35prd_10.monthly
cus_000522026-07-05 21:18:40prd_14.annual
cus_000532026-09-23 14:34:48prd_04.monthly
cus_000542026-04-06 08:10:51prd_05.annual
cus_000552026-06-29 08:52:26prd_09.monthly
cus_000562025-02-14 10:17:52prd_12.weekly
cus_000572026-03-14 23:44:21prd_12.weekly
cus_000582025-12-03 19:25:42prd_08.annual
cus_000592025-12-29 22:58:47prd_15.monthly
cus_000602025-09-08 19:20:21prd_02.annual
cus_000612026-05-25 21:13:55prd_18.annual
cus_000622025-10-22 19:54:03prd_08.annual
cus_000632026-04-13 10:59:59prd_17.annual
cus_000642025-12-30 00:47:55prd_08.monthly
cus_000652026-09-27 07:58:25prd_15.monthly
cus_000662025-10-30 12:19:56prd_05.annual
cus_000672026-07-25 13:19:02prd_07.annual
cus_000682026-08-22 13:52:21prd_04.annual
cus_000692025-08-22 23:34:49prd_01.annual
cus_000702025-08-05 03:32:19prd_04.weekly
cus_000712026-07-07 04:35:05prd_19.monthly
cus_000722026-06-17 21:36:52prd_04.annual
cus_000732025-03-04 17:26:21prd_20.monthly
cus_000742025-03-16 04:35:40prd_13.annual
cus_000752025-08-12 04:09:56prd_16.monthly
cus_000762025-03-10 03:19:17prd_20.monthly
cus_000772026-08-27 12:00:07prd_04.weekly
cus_000782026-04-01 20:15:10prd_05.monthly
cus_000792026-03-31 11:50:00prd_20.weekly
cus_000802026-01-11 10:18:18prd_12.monthly
cus_000812025-08-09 18:39:14prd_13.monthly
cus_000822025-02-23 08:01:43prd_20.annual
cus_000832025-08-06 04:42:12prd_09.monthly
cus_000842026-04-17 20:57:45prd_02.monthly
cus_000852025-12-14 08:04:01prd_12.annual
cus_000862025-12-26 23:29:59prd_04.annual
cus_000872026-09-01 22:51:46prd_18.monthly
cus_000882026-06-04 02:15:09prd_19.annual
cus_000892026-08-21 19:01:57prd_02.monthly
cus_000902025-10-18 09:10:29prd_10.annual
cus_000912025-11-14 23:53:10prd_10.annual
cus_000922025-05-18 19:09:55prd_09.annual
cus_000932025-08-20 05:00:30prd_07.monthly
cus_000942026-02-08 12:15:40prd_15.annual
cus_000952026-02-21 14:57:32prd_18.annual
cus_000962026-03-18 13:23:33prd_08.monthly
cus_000972026-04-04 08:05:02prd_13.annual
cus_000982026-09-23 03:36:27prd_12.monthly
cus_000992026-05-10 04:02:53prd_05.monthly
cus_001002026-08-12 08:48:31prd_15.monthly
2600 rows (first 100 shown)

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.

TalkSay it out loud

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.”

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.”

  1. 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”.
  2. 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.”
  3. Wrap, do not rewrite: the working query becomes the first CTE, without its ORDER BY.
  4. 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.

SQLWrite a querycore

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.id
  • start_time — start of the period = time of purchase; "started in …" means this column
  • revenue_usd — revenue net of refunds: 0 if the transaction was refunded (net)
  • is_test — test purchase: exclude it from business numbers
product_idstart_timerevenue_usdis_test
prd_012025-01-05 05:52:570.00false
prd_012025-01-03 05:03:116.99false
prd_012025-01-10 11:02:396.99false

products — products (20 rows); a merchant can own several

  • id — key: prd_01 …
  • merchant_id — → merchants.id
idmerchant_id
prd_01mer_01
prd_02mer_02
prd_03mer_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_usd
FROM ranked
WHERE rn = 1
ORDER BY merchant_id;

Expected output

merchant_idproduct_idnet_usd
mer_01prd_01264.81
mer_02prd_02542.84
mer_03prd_03389.82
mer_04prd_04155.64
mer_05prd_05249.81
mer_06prd_18313.80
mer_07prd_07225.80
mer_08prd_08314.53
mer_09prd_09321.86
mer_10prd_14223.83
mer_11prd_11195.81
mer_12prd_15659.76
12 rows

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.

SQLWrite a query

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.id
  • channel — 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 column
  • is_test — test purchase: exclude it from business numbers
product_idchannelis_trialstart_timeis_test
prd_01promofalse2025-01-05 05:52:57false
prd_01north_marketfalse2025-01-03 05:03:11false
prd_01north_marketfalse2025-01-10 11:02:39false

"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, rnk
FROM r
WHERE rnk <= 5
ORDER BY rnk, product_id;

Expected output

product_idtransactionsrnk
prd_08491
prd_04362
prd_20293
prd_12284
prd_15255
prd_16255
6 rows

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.

SQLWrite a querycore

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 transaction
  • customer_id — the customer
  • product_id — → products.id
  • plan_id — plan, e.g. prd_03.monthly
  • start_time — start of the period = time of purchase; "started in …" means this column
  • is_test — test purchase: exclude it from business numbers
transaction_idcustomer_idproduct_idplan_idstart_timeis_test
t_000001cus_00001prd_03prd_03.annual2025-10-12 16:30:29false
t_000002cus_00002prd_08prd_08.weekly2025-06-25 19:26:50false
t_000003cus_00003prd_19prd_19.monthly2025-02-27 08:20:21false

"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_time
FROM ranked
WHERE rn = 1
ORDER BY customer_id;

Expected output

customer_idplan_idstart_time
cus_00001prd_03.annual2025-10-12 16:30:29
cus_00010prd_03.annual2026-09-05 14:42:03
cus_00030prd_03.annual2026-08-08 02:20:18
cus_00046prd_03.monthly2025-06-05 05:25:55
cus_00156prd_03.monthly2026-05-01 01:04:43
cus_00183prd_03.annual2026-03-13 19:27:28
cus_00186prd_03.annual2026-02-23 14:25:49
cus_00187prd_03.monthly2025-04-10 00:17:36
cus_00222prd_03.annual2026-04-28 17:48:26
cus_00227prd_03.monthly2025-11-30 10:03:22
cus_00279prd_03.monthly2025-12-06 01:22:45
cus_00281prd_03.monthly2026-01-09 18:18:27
cus_00290prd_03.monthly2026-09-19 21:04:37
cus_00293prd_03.monthly2026-06-22 13:09:09
cus_00303prd_03.annual2026-02-08 13:59:34
cus_00323prd_03.annual2026-02-11 11:15:49
cus_00338prd_03.monthly2025-07-07 21:30:20
cus_00350prd_03.annual2025-10-29 00:30:00
cus_00372prd_03.monthly2026-09-14 13:39:43
cus_00383prd_03.monthly2026-08-28 15:03:10
cus_00385prd_03.monthly2025-04-28 21:33:36
cus_00393prd_03.annual2026-07-07 21:06:13
cus_00416prd_03.monthly2026-09-06 07:14:10
cus_00425prd_03.monthly2026-05-09 08:41:18
cus_00428prd_03.monthly2026-09-24 05:28:46
cus_00436prd_03.annual2025-12-10 02:24:25
cus_00487prd_03.annual2026-04-02 00:44:48
cus_00543prd_03.monthly2026-04-19 00:52:28
cus_00564prd_03.annual2026-08-03 15:58:18
cus_00586prd_03.monthly2026-05-23 23:05:47
cus_00592prd_03.annual2026-05-27 09:47:41
cus_00595prd_03.annual2025-03-07 12:27:26
cus_00602prd_03.annual2026-04-24 06:07:07
cus_00615prd_03.monthly2026-01-01 23:58:41
cus_00667prd_03.annual2026-08-16 23:49:09
cus_00672prd_03.monthly2026-04-24 16:57:43
cus_00723prd_03.annual2026-09-06 21:07:44
cus_00736prd_03.monthly2026-09-16 16:04:32
cus_00737prd_03.monthly2026-09-13 02:50:42
cus_00777prd_03.annual2026-01-21 00:32:12
cus_00819prd_03.annual2026-05-21 15:41:45
cus_00828prd_03.monthly2026-09-16 08:55:18
cus_00832prd_03.monthly2025-09-24 12:28:04
cus_00841prd_03.monthly2025-10-10 11:11:57
cus_00869prd_03.annual2025-04-18 09:05:39
cus_00902prd_03.annual2026-09-21 00:44:33
cus_00912prd_03.annual2026-06-15 01:17:58
cus_00927prd_03.annual2025-11-04 14:19:52
cus_00937prd_03.monthly2025-12-16 14:22:09
cus_01009prd_03.monthly2026-09-01 04:31:10
cus_01127prd_03.monthly2026-09-11 13:13:38
cus_01140prd_03.annual2026-01-28 22:25:03
cus_01149prd_03.annual2026-01-27 23:56:43
cus_01161prd_03.annual2025-02-19 23:03:26
cus_01170prd_03.monthly2025-07-25 17:32:37
cus_01182prd_03.monthly2026-09-24 04:31:35
cus_01192prd_03.annual2026-06-08 18:11:34
cus_01250prd_03.annual2025-05-25 17:15:45
cus_01269prd_03.annual2026-01-07 10:15:08
cus_01289prd_03.annual2025-09-27 08:01:54
cus_01303prd_03.annual2025-07-30 04:25:41
cus_01316prd_03.monthly2026-05-11 15:35:33
cus_01327prd_03.annual2025-05-21 20:43:40
cus_01336prd_03.annual2026-09-25 13:07:30
cus_01352prd_03.monthly2025-03-30 01:42:59
cus_01414prd_03.annual2026-02-27 02:47:12
cus_01424prd_03.monthly2026-08-29 09:54:26
cus_01438prd_03.annual2026-05-18 10:36:57
cus_01445prd_03.annual2026-03-12 17:28:38
cus_01464prd_03.annual2026-05-09 14:36:58
cus_01476prd_03.annual2025-11-02 05:17:10
cus_01497prd_03.monthly2026-05-07 16:54:49
cus_01516prd_03.monthly2025-12-30 00:21:41
cus_01559prd_03.monthly2026-09-01 06:53:11
cus_01691prd_03.monthly2026-05-20 21:32:32
cus_01694prd_03.annual2026-04-16 23:00:37
cus_01696prd_03.annual2026-04-24 23:56:35
cus_01700prd_03.monthly2026-09-11 22:20:23
cus_01733prd_03.annual2026-07-24 00:47:07
cus_01771prd_03.monthly2025-06-21 22:37:59
cus_01772prd_03.annual2026-06-24 02:25:52
cus_01774prd_03.annual2025-08-13 08:54:08
cus_01796prd_03.monthly2025-09-27 08:08:53
cus_01809prd_03.annual2025-08-23 22:31:14
cus_01818prd_03.annual2026-05-01 00:19:18
cus_01838prd_03.monthly2026-05-27 20:18:12
cus_01843prd_03.annual2026-07-31 07:51:24
cus_01849prd_03.monthly2026-03-22 23:09:59
cus_01883prd_03.annual2026-01-07 07:07:40
cus_01948prd_03.annual2026-01-29 20:53:43
cus_01949prd_03.annual2025-06-04 19:46:22
cus_02021prd_03.annual2026-04-15 21:07:22
cus_02044prd_03.annual2026-03-14 21:18:52
cus_02045prd_03.annual2025-01-02 01:42:24
cus_02049prd_03.annual2026-05-12 17:30:05
cus_02074prd_03.monthly2026-03-15 06:29:02
cus_02097prd_03.monthly2025-08-25 21:24:52
cus_02109prd_03.monthly2025-02-22 17:04:30
cus_02168prd_03.annual2026-04-14 12:07:16
cus_02170prd_03.annual2025-11-16 07:47:52
116 rows (first 100 shown)

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.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.