capypad
0 day streak
sql / expert
Snippet

Lateral Derived Tables for Row-Wise Calculations

The LATERAL keyword (part of ANSI SQL) allows a subquery in the FROM clause to reference columns of preceding tables in the same FROM clause. This is powerful for 'top-N per group' queries or performing complex calculations for each row that require context from the outer table.

snippet.sql
sql
1
2
3
4
5
6
7
8
9
SELECT u.name, top_order.amount
FROM users u
CROSS JOIN LATERAL (
SELECT amount
FROM orders o
WHERE o.user_id = u.id
ORDER BY o.amount DESC
FETCH FIRST 1 ROW ONLY
) AS top_order;
Breakdown
1
CROSS JOIN LATERAL (
Initiates a lateral join, allowing the subquery to see 'u.id'.
2
WHERE o.user_id = u.id
References the outer table's column within the subquery scope.
3
FETCH FIRST 1 ROW ONLY
Limits the result set for each specific user to their highest order.