What is the difference between LATERAL joins and correlated subqueries?

Answer

A LATERAL join allows a subquery in the FROM clause to reference columns from preceding tables — it's like a correlated subquery but in FROM position, and can return multiple rows and columns. Without LATERAL, a subquery in FROM cannot see outer tables. Example: get the last 3 orders for each user: SELECT u.name, o.* FROM users u, LATERAL (SELECT * FROM orders WHERE user_id = u.id ORDER BY created_at DESC LIMIT 3) o;. A correlated subquery in SELECT/WHERE also references the outer query but is re-executed for every outer row — the planner may or may not optimize this as a join. LATERAL joins are often faster because the planner can choose efficient join strategies. LATERAL is required when the function returns rows based on the outer row: CROSS JOIN LATERAL unnest(tags) AS tag or LEFT JOIN LATERAL function(u.id) ON true.