How-To Guide

How to Use LATERAL Joins for Top-N-per-Group

Use LATERAL joins to fetch the top N rows per group efficiently, compare with window functions, and index the inner query for speed.

On this page

  1. Introduction
  2. Choose between LATERAL and a window function
  3. Write the correlated LATERAL query
  4. Index the inner query so each group seeks
  5. Verify the plan and the results
  6. Test boundaries and per-group correctness
  7. Common pitfalls
  8. Conclusion

Introduction

Fetching the top few rows per group is a question that appears constantly: the latest order per customer, the three highest-paid employees per department, the newest event per device. The naive approach ranks the entire table with a window function, which is correct but reads every row even when only a handful per group are wanted. A LATERAL join takes a different approach: for each group, run a small indexed query that returns just its N rows.

This tutorial compares LATERAL joins and window functions for top-N-per-group, shows how to write and index a LATERAL query so each group’s inner query is a seek, and how to verify with the plan and results that each group returns the right rows. The examples use PostgreSQL, whose LATERAL feature lets a subquery reference the outer row.

Choose between LATERAL and a window function

A window function computes a rank or row number across a partition and then filters to the top N. It reads all rows in each partition and sorts them, once for the whole query. That is efficient when you need the top N across the entire dataset or when the groups are few and the partitions must be fully ordered anyway. It is wasteful when there are many groups and each needs only a couple of rows.

A LATERAL join runs a subquery per outer row, correlated on the group key, and orders and limits inside. It reads only the rows each group needs, provided an index lets the inner query seek. That is efficient for many small groups, the common case of ‘latest per customer’. Choose LATERAL for many groups with a small N, and a window function for a global ranking or when the inner query cannot be indexed to limit its scan.

-- window function: rank everything, then keep the top 3 per customer
SELECT * FROM (
  SELECT *,
         row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
  FROM orders
) t
WHERE rn <= 3;

Write the correlated LATERAL query

The LATERAL keyword lets the right-hand subquery reference columns from the left-hand table. For top-N-per-group, the outer query lists the groups and the lateral subquery selects and orders the group’s rows, limiting to N. The database evaluates the subquery once per outer row, producing exactly N rows for each group instead of ranking the entire table.

This shape is especially clear when the outer query filters groups, because only the surviving groups run their inner query. If you only need the latest order for customers who are active, filter the customers first and then laterals run for those customers alone. The plan shows a nested loop with the outer side driving and the lateral as the inner probe.

-- top 3 recent orders per customer
SELECT c.id AS customer_id, o.id AS order_id, o.created_at, o.total
FROM customers c
CROSS JOIN LATERAL (
  SELECT o.id, o.created_at, o.total
  FROM orders o
  WHERE o.customer_id = c.id
  ORDER BY o.created_at DESC
  LIMIT 3
) o;

Index the inner query so each group seeks

For the LATERAL query to be fast, the inner query must find its group’s rows without scanning. A composite index on (customer_id, created_at DESC) lets the inner query seek the customer and read the top three in order, so the cost per group is a small index range, not a scan of the whole orders table. This is the single change that turns a slow LATERAL into a fast one.

The index order must match the inner query’s filter and sort: the equality filter on customer_id leads, and the sort column created_at follows, marked DESC if the query orders descending so the index can be read forward. If the inner query filters on more than the group key, include those columns in the index between the key and the sort, matching the query’s predicates in order.

-- index that makes each lateral probe a seek
CREATE INDEX CONCURRENTLY idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

Verify the plan and the results

Read EXPLAIN and look for a nested loop whose outer side scans the groups and whose inner side is an index scan on orders, with a loop count equal to the number of groups. If the inner side is a sequential scan, the index is missing or not matching the query, and each group is scanning the whole table. The loop count tells you how many times the inner query ran, which should equal the groups you asked for.

Check the results against the definition: exactly N rows per group when the group has at least N, fewer when it has less, ordered as specified. An off-by-one in the limit or a wrong sort direction is easy to miss in a large result, so verify with a small group that has fewer than N rows and a large group at the boundary.

Nested Loop  (actual rows=300)
  ->  Seq Scan on customers c  (actual rows=100)
  ->  Index Scan using idx_orders_customer_created on orders o
        Index Cond: (customer_id = c.id)
        -- loops=100 (one per customer), rows=3 each

Test boundaries and per-group correctness

Seed a customer with more than N orders and assert exactly N come back in the right order. Seed a customer with fewer than N and assert all of them return without error. Seed a customer with zero orders and assert it returns no rows for that group but does not drop the other groups. Assert the total row count equals the sum of the per-group counts, which catches a join that accidentally multiplies or omits groups.

psql -d app <<'SQL'
-- customer 1 has 5 orders, customer 2 has 2, customer 3 has 0
SELECT c.id, count(o.*) FROM customers c
LEFT JOIN LATERAL (SELECT * FROM orders WHERE customer_id=c.id ORDER BY created_at DESC LIMIT 3) o ON true
GROUP BY c.id ORDER BY c.id;
-- expect 3, 2, 0
SQL

Common pitfalls

Using a window function for many small groups so it ranks the whole table, a LATERAL inner query without an index on the group key and sort column, a sort direction in the index opposite to the query, forgetting that a group with fewer than N rows returns fewer, and an inner join that drops groups with no rows are the recurring mistakes. Choosing LATERAL for small groups, indexing the inner query, matching order, and using an outer join address them.

Conclusion

Top-N-per-group is a LATERAL join when there are many groups that each want a few indexed rows, and a window function when you need a global ranking. Write the inner query correlated on the group key, index (group_key, sort_column) so each probe seeks, verify the nested loop and loop count in the plan, and test the boundaries. Self-check by asserting a group with fewer than N returns all its rows and a group with none returns zero without dropping others. Then each group pays only for the rows it needs.

Sources: PostgreSQL: LATERAL subqueries, PostgreSQL: Window functions, PostgreSQL: Row estimation and LIMIT.

FAQ

LATERAL join or window function?
A LATERAL join runs the inner query once per group, which is efficient when each group has an index that finds its top rows fast. A window function ranks the whole set in one pass, which is better when you need the top N across all rows or the groups are large and unsorted.
Why is my LATERAL join slow?
Usually the inner query has no index on the group key and sort column, so each of the many probes is a scan. Add a composite index on (group_key, sort_column) so the inner query seeks and returns only its N rows.

Related Examples