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
1
2
3
4
5
6
7
8
9
SELECT u.name, top_order.amountFROM users uCROSS JOIN LATERAL (SELECT amountFROM orders oWHERE o.user_id = u.idORDER BY o.amount DESCFETCH 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.