Groupwise Top-N: ROW_NUMBER() vs LATERAL + LIMIT

The 3 most recent orders for each of 1,000 VIP customers. Written with ROW_NUMBER(), the query joins and sorts all 20,000 customer orders and then keeps 3 per customer. Reading only 3 entries backward from the index for each customer inside LATERAL applies partial range processing per customer. The scenario also shows the conclusion reversing when the number of groups grows.

SQL

Situation

A VIP management screen shows the 3 most recent orders for each customer. There are 1,000 VIPs, and customer 100 among them is a high-volume B2B customer with more than 2,000 orders. The query uses the common ROW_NUMBER() pattern. The result is 3,000 rows, yet it takes longer than expected.

Tables

TableColumnsDescription
customersgrade, cust_nm1,000 VIPs
orderscust_id, ord_dt, amt20,080 orders of VIP customers
IndexColumns
customers_x1grade
orders_x1cust_id, ord_dt

Query

BEFORE · Filter after ROW_NUMBER()

SELECT cust_id, cust_nm, ord_id, ord_dt, amt
FROM (
  SELECT c.cust_id, c.cust_nm, o.ord_id, o.ord_dt, o.amt,
         ROW_NUMBER() OVER (PARTITION BY c.cust_id ORDER BY o.ord_dt DESC) AS rn
  FROM customers c
  JOIN orders o ON o.cust_id = c.cust_id
  WHERE c.grade = 'VIP'
) t
WHERE rn <= 3
ORDER BY cust_id, ord_dt DESC

Run it and look at the row count that enters the Sort under WindowAgg and at how orders is read.

Approach

1. Work out what one customer needs

The 3 most recent orders of one customer come from reading 3 entries backward from the end of the cust_id = ? range in orders_x1. This is Top-N partial range processing done per customer. Even a customer with 2,000 orders, such as customer 100, needs only 3 entries read.

2. Check whether the window function can stop

rn <= 3 is a condition applied after the window function is fully computed. From PostgreSQL 15, a Run Condition stops the numbering early, but the join and sort below it have already received every row. This is not partial range processing; it is "build everything, then discard".

3. Express "repeat per customer" in the query

If a subquery runs once per customer and uses ORDER BY … LIMIT 3 inside it, each iteration reads only 3 entries from the index. This is the shape of an NL join. Conversely, with a very large number of customers, the repeated probes can cost more than a full read. The number of groups is the deciding factor.

Explanation

Read only 3 rows per customer inside LATERAL

AFTER · LATERAL + LIMIT 3

SELECT c.cust_id, c.cust_nm, o.ord_id, o.ord_dt, o.amt
FROM customers c
CROSS JOIN LATERAL (
  SELECT ord_id, ord_dt, amt
  FROM orders
  WHERE orders.cust_id = c.cust_id
  ORDER BY ord_dt DESC
  LIMIT 3
) o
WHERE c.grade = 'VIP'
ORDER BY c.cust_id, o.ord_dt DESC

Why it got faster

  • Before reads 2 million orders rows with a Seq Scan (18,752 blocks), hash-joins them with the VIP customers, sorts the resulting 20,080 rows by (cust_id, ord_dt DESC), and then WindowAgg keeps 3,000 rows. Buffers 19,589. All 2,000-odd orders of customer 100 are joined and sorted too.
  • After finds the 1,000 VIPs through customers_x1 (837 blocks), and for each customer Index Scan Backward using orders_x1 stops at the Limit of 3 rows (Starts 1,000, about 6 blocks per iteration: 3 index + 3 table). Buffers 6,848. Customer 100 also reads only 3 rows.
  • The final Sort is a small sort that puts the 3,000 rows in customer order.

Why this is optimal

  • The remaining cost is "number of customers × 6 blocks". Reading 3 result rows requires one index descent and reading the table blocks that hold the 3 rows, so the per-customer cost is hard to reduce further.
  • The 837 blocks for finding customers come from VIP customers being scattered across the whole table. That stays the same unless the customer table changes.

Variation: with many groups the conclusion reverses

Using the same LATERAL for the 90,000 regular customers means 90,000 repeated probes.

TRY · NORMAL customers (LATERAL)

SELECT c.cust_id, c.cust_nm, o.ord_id, o.ord_dt, o.amt
FROM customers c
CROSS JOIN LATERAL (
  SELECT ord_id, ord_dt, amt
  FROM orders
  WHERE orders.cust_id = c.cust_id
  ORDER BY ord_dt DESC
  LIMIT 3
) o
WHERE c.grade = 'NORMAL'
ORDER BY c.cust_id, o.ord_dt DESC

TRY · NORMAL customers (hash join + ROW_NUMBER)

SET LOCAL enable_mergejoin = off;
SET LOCAL enable_nestloop = off;
SELECT cust_id, cust_nm, ord_id, ord_dt, amt
FROM (
  SELECT c.cust_id, c.cust_nm, o.ord_id, o.ord_dt, o.amt,
         ROW_NUMBER() OVER (PARTITION BY c.cust_id ORDER BY o.ord_dt DESC) AS rn
  FROM customers c
  JOIN orders o ON o.cust_id = c.cust_id
  WHERE c.grade = 'NORMAL'
) t
WHERE rn <= 3
ORDER BY cust_id, ord_dt DESC
  • LATERAL uses about 542,000 Buffers. That equals reading the whole table (18,752 blocks) 29 times.
  • Hash join + ROW_NUMBER() uses about 19,600 Buffers, but sorting 1.8 million rows exceeds work_mem (16MB), so it writes and reads about 10,000 TEMP blocks (external merge).
  • In this sandbox every block is in memory, so the LATERAL side sometimes even finishes sooner. In an environment that must read from disk, 540,000 random block reads are far more expensive. When block counts and timings give different answers, judge by the cache state of the production environment.
  • Run without the planner settings, the planner picks a Merge Join that reads all of orders_x1 in order. In this data the orders_x1 order differs from the table order, so Buffers exceed 2 million (scenario 14).

Key points

Groups × rows per groupBetter approachReason
Few groups, many rows per groupLATERAL + ORDER BY … LIMITStops at N rows per group through the index
Very many groups (most of the table)Full read + ROW_NUMBER()Repeated probes cost more than a full read
  • ROW_NUMBER() … WHERE rn <= N is a statement that builds the whole result and then filters it. For partial range processing, write the "stop at N rows per group" shape directly.
  • Groupwise Top-N needs an index in group key + sort key order. Here that is orders_x1 (cust_id, ord_dt).
  • Differences by DB: Oracle uses the same shape with CROSS APPLY/LATERAL and FETCH FIRST from 12c. SQL Server uses CROSS APPLY (SELECT TOP 3 …).