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.
Previous
How do you use EXPLAIN ANALYZE effectively in PostgreSQL?
Next
What is pg_partman and how does it simplify partition management?
More PostgreSQL Questions
View all →- Advanced What is the query planner in PostgreSQL and how does it work?
- Advanced What causes poor query plans and how do you fix them?
- Advanced What is logical replication in PostgreSQL?
- Advanced How do you implement row-level security (RLS) in PostgreSQL?
- Advanced What is table bloat in PostgreSQL and how do you fix it?