LATERAL & Range Joins in SQL
Per-row subqueries and band lookups
LATERAL (PG) runs a per-row subquery — each left row gets its own LIMITed lookup (top-N per group, index-friendly). Range/band joins use inequality ON (salary BETWEEN lo AND hi; event BETWEEN start AND end-effective) for pay grades and point-in-time versioning. Correct but heavier (nested-loop-ish); composite/covering indexes on range columns help. Half-open ends keep effective-dating exact.
LATERAL per row
JOIN LATERAL (… LIMIT N) — each left row runs its own indexed lookup. Top-N per group.
Range ON bands
salary BETWEEN lo AND hi; event >= start AND < end — non-equi matching.
Half-open effective
Point-in-time correctness lives on the exclusive end.
Index the probe
Composite/covering on range cols; LATERAL wants inner ORDER + LIMIT index.
1-- salary band lookup:2SELECT e.name, b.band FROM employees e JOIN pay_bands b ON e.salary BETWEEN b.lo AND b.hi LIMIT 2;
| name | band |
|---|---|
| Alice | L4 |
| Bob | L2 |
Each salary probes the band table by range, not equality. LATERAL generalizes this to per-employee latest-orders lookups with LIMIT inside — impossible in plain JOIN.
Pay bands by range
No equality key — range probe.
1SELECT e.name, b.band FROM employees e JOIN pay_bands b ON e.salary BETWEEN b.lo AND b.hi LIMIT 2;
| name | band |
|---|---|
| Alice | L4 |
| Bob | L2 |
Recent orders per customer (PG)
Per-customer LIMIT impossible in plain JOIN.
1SELECT c.name, r.id FROM customers c JOIN LATERAL (SELECT id FROM orders o WHERE o.customer_id = c.id ORDER BY created_at DESC LIMIT 2) r ON true;
| customer | order_id |
|---|---|
| Ada | 501 |
| Ada | 498 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.