PostgreSQL LATERAL Join Top N Per Group

Fetch the latest N rows per group with a LATERAL join driving an indexed subquery per outer row, avoiding giant windows.

SqlData Fetching

Code

sqlsnippet
34 lines
-- PostgreSQL LATERAL:外层每行驱动内层子查询一次
SELECT
  c.id AS customer_id,
  c.email,
  latest.order_id,
  latest.total_cents,
  latest.placed_at
FROM customers c
LEFT JOIN LATERAL (
  SELECT o.id AS order_id, o.total_cents, o.placed_at
  FROM orders o
  WHERE o.customer_id = c.id
  ORDER BY o.placed_at DESC
  LIMIT 3
) latest ON true
WHERE c.region = 'eu'
ORDER BY c.id, latest.placed_at DESC;

-- 对照窗口函数版本:全量开窗后过滤
SELECT customer_id, order_id, total_cents, placed_at
FROM (
  SELECT
    customer_id, id AS order_id, total_cents, placed_at,
    ROW_NUMBER() OVER (
      PARTITION BY customer_id
      ORDER BY placed_at DESC
    ) AS rn
  FROM orders
) ranked
WHERE rn <= 3;

-- 支撑索引:内层子查询的 LIMIT 才能秒回
CREATE INDEX idx_orders_customer_time
  ON orders (customer_id, placed_at DESC);

How it works

Several statements share this file — SELECT / CREATE, with customers, lateral and orders among the objects involved.

Concretely, the SQL combines: one JOIN combining rows across tables; a WHERE clause that picks out the rows one statement touches; a window function (OVER (…)) calculating values across rows while every row stays visible; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

What to watch for

  • Window output exists only after grouping — filter it from an enclosing query, not the same one.

Applying it

Run the statement against the customers table; the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

SELECT customer_id, order_id, total_cents, placed_at
FROM (
SELECT
customer_id, id AS order_id, total_cents, placed_at,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY placed_at DESC
) AS rn
FROM orders
) ranked
WHERE rn <= 3;
CREATE INDEX idx_orders_customer_time
ON orders (customer_id, placed_at DESC);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`customers`, `lateral`, `orders` — joined via one JOIN clause.