sqladvanced
SQL LATERAL Join Examples
Use LATERAL joins to run correlated subqueries for top-N per group and row-dependent lookups.
sqlPress ⌘/Ctrl + Shift + C to copy
-- Top 3 orders per customer using LATERAL
SELECT c.id, c.name, o.id AS order_id, o.amount, o.created_at
FROM customers c
CROSS JOIN LATERAL (
SELECT id, amount, created_at
FROM orders
WHERE customer_id = c.id
ORDER BY amount DESC
LIMIT 3
) o;
-- Latest order per customer
SELECT c.id, c.name, latest.amount, latest.created_at
FROM customers c
LEFT JOIN LATERAL (
SELECT amount, created_at
FROM orders
WHERE customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) latest ON TRUE;
-- Running total with LATERAL
SELECT
o.id,
o.amount,
o.created_at,
running.total AS running_total
FROM orders o
CROSS JOIN LATERAL (
SELECT SUM(amount) AS total
FROM orders
WHERE created_at <= o.created_at
) running
ORDER BY o.created_at;
-- Expand array/JSON elements
SELECT
p.id,
p.name,
t.tag
FROM products p
CROSS JOIN LATERAL UNNEST(p.tags) AS t(tag);
-- Computed columns referencing previous columns
SELECT *
FROM orders,
LATERAL (
SELECT
amount * 0.1 AS tax,
amount * 0.9 AS net
) calc,
LATERAL (
SELECT calc.net - shipping_cost AS profit
) profit_calc;Use Cases
- Top-N per group queries efficiently
- Row-dependent correlated lookups
- Expanding arrays and JSON into rows
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqladvanced
LATERAL Join for Correlated Subqueries
Use LATERAL join to reference columns from preceding tables in subqueries.
Best for: Top-N per group queries
#sql#lateral
sqlbeginner
Join - Technique 19
Advanced join techniques
Best for: database operations
#sql#database
sqladvanced
Recursive CTE for Hierarchical Data
Query hierarchical data like org charts, categories, and file trees using recursive CTEs.
Best for: Querying organizational hierarchies
#sql#cte
sqlintermediate
SQL Pivot and Crosstab Queries
Transform row data into columnar reports using CASE expressions, FILTER, and crosstab patterns.
Best for: Creating monthly revenue reports
#sql#pivot