LATERAL JOIN
advancedadvanced
2 min read
What is a LATERAL JOIN?
LATERAL allows a subquery in the FROM clause to reference columns from tables that appear before it in the FROM list. Without LATERAL, subqueries in FROM cannot see the outer query's columns.
Syntax
SELECT a.*, b.*
FROM table_a a
CROSS JOIN LATERAL (
SELECT * FROM table_b b
WHERE b.a_id = a.id
ORDER BY b.created_at DESC
LIMIT 3
) AS b;SELECT a.*, b.*
FROM table_a a
LEFT JOIN LATERAL (
SELECT * FROM table_b b
WHERE b.a_id = a.id
LIMIT 1
) AS b ON true;When to Use
- Getting the top-N related rows per parent row
- Replacing correlated subqueries in SELECT for better performance
- Calling set-returning functions with per-row arguments
Key Points
- Row-Dependent — The LATERAL subquery can use columns from preceding FROM items.
- CROSS JOIN LATERAL — Excludes parent rows with no matches.
- LEFT JOIN LATERAL — Keeps all parent rows (NULLs for no matches).
- ON true — For LEFT JOIN LATERAL, use ON true since the condition is inside the subquery.
- Performance — Often more efficient than correlated subqueries in SELECT.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
LATERAL JOIN Challenge
Write a query that solve this task: get each student with their 2 most recent enrollments.
Expected result
Each student with up to 2 of their most recent enrollments.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is a LATERAL JOIN?
Initializing database...Each run starts from fresh sample data.
More Examples
Nearest product by price
For each order, find the product closest in price.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What is the difference between LATERAL and a regular subquery in FROM?
A regular subquery in FROM cannot reference other tables in the FROM clause. LATERAL allows this cross-reference.
Is LATERAL a PostgreSQL-only feature?
No. LATERAL is part of the SQL standard and is supported by PostgreSQL, MySQL 8+, and other modern databases.