📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PostgreSQL Essentials Lateral Joins

Lateral Joins

6 min read
LATERAL lets a subquery reference columns from earlier in the FROM clause for per-row computation. It is perfect for efficiently fetching the top N rows per group, like the 3 most recent orders for each user.

LATERAL Joins

-- Get last 3 orders per user
SELECT u.name, o.total, o.created
FROM users u
CROSS JOIN LATERAL (
  SELECT total, created FROM orders
  WHERE user_id = u.id
  ORDER BY created DESC
  LIMIT 3
) o;

LATERAL lets a subquery reference columns from the outer query — like a correlated subquery that returns multiple rows.