Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Master SQL LATERAL joins across PostgreSQL and MySQL 8. Learn how to write correlated subqueries in FROM clauses and solve the classic top-N per group problem.
Quick answer
A SQL LATERAL join allows a subquery in the FROM clause to reference columns from preceding tables in the same query. It functions like a correlated subquery evaluated for each row of the outer table, making it the ideal solution for calculating top-N records per category and unpacking nested collections.
FAQs
What is the difference between LATERAL in PostgreSQL and CROSS APPLY in SQL Server?
They are functionally identical. PostgreSQL uses the ANSI SQL standard LATERAL keyword, while SQL Server uses the proprietary CROSS APPLY and OUTER APPLY syntax.
Does SQLite support LATERAL joins?
SQLite does not support the LATERAL keyword directly. However, starting in SQLite 3.35, table-valued functions and certain subqueries can accept outer column references.
Can a LATERAL subquery return multiple rows?
Yes. A LATERAL subquery can return multiple rows, which produces a standard Cartesian product for that parent row, exactly like a regular join.
Is JOIN LATERAL faster than ROW_NUMBER()?
JOIN LATERAL is significantly faster when filtering a subset of parent records and a composite index exists on the child table, because it reads only the needed rows rather than partitioning the entire table.
In standard SQL queries, tables and derived subqueries in the FROM clause execute in isolation. A subquery in the FROM clause cannot reference columns from preceding tables in the join list. Attempting to do so triggers an unknown column or invalid scope error.
The LATERAL keyword changes this rule. A LATERAL join allows a derived subquery to act as a correlated subquery, reading column values from earlier tables in the FROM clause for each row processed. It solves complex queries like retrieving the top-3 most recent orders for every customer with clean, readable syntax.
Why standard subqueries cannot reference preceding tables
Under ANSI SQL rules, all tables listed in the FROM clause are evaluated as independent sets before join conditions are evaluated. Review our guide to SQL join formatting for foundational join structure.
The invalid cross-scope subquery error
-- Invalid standard query: fails with errorSELECT c.customer_id, recent_orders.order_id, recent_orders.totalFROM customers cJOIN ( SELECT o.order_id, o.total FROM orders o WHERE o.customer_id = c.customer_id -- ERROR: c.customer_id is out of scope! ORDER BY o.order_date DESC LIMIT 3) AS recent_orders ON true;
Without the LATERAL keyword, the inner subquery cannot see c.customer_id. Developers often work around this using window functions like ROW_NUMBER(), which requires scanning the entire orders table before filtering.
The LATERAL solution: correlated derived tables
Adding LATERAL before the subquery permits the subquery to reference columns provided by previous tables in the FROM clause. In SQL Server, this same capability is implemented via CROSS APPLY and OUTER APPLY. Read our detailed guide on SQL Server CROSS APPLY and OUTER APPLY for T-SQL comparisons.
Solving Top-N per group with LEFT JOIN LATERAL
SELECT c.customer_id, c.company_name, latest.order_id, latest.order_date, latest.total_amountFROM customers cLEFT JOIN LATERAL ( SELECT o.order_id, o.order_date, o.total_amount FROM orders o WHERE o.customer_id = c.customer_id -- Fully valid with LATERAL! ORDER BY o.order_date DESC LIMIT 3) AS latest ON trueORDER BY c.customer_id, latest.order_date DESC;
Using LEFT JOIN LATERAL ... ON true ensures that customers with zero orders still appear in the output with NULL values. If you want to omit customers without orders, use CROSS JOIN LATERAL instead.
Performance comparison: LATERAL vs Window Functions
The traditional way to solve top-N per group is wrapping ROW_NUMBER() in a Common Table Expression:
Alternative approach using ROW_NUMBER()
WITH ranked_orders AS ( SELECT customer_id, order_id, order_date, total_amount, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY order_date DESC ) AS rn FROM orders)SELECT customer_id, order_id, order_date, total_amountFROM ranked_ordersWHERE rn <= 3;
When querying a small subset of customers (for instance, customers in one specific city), the ROW_NUMBER() query must scan the entire orders table. In contrast, JOIN LATERAL leverages an index on orders (customer_id, order_date DESC) to jump directly to the top 3 orders per matching customer, cutting disk reads dramatically.
LATERAL joins in MySQL 8.0
MySQL added support for lateral derived tables in MySQL 8.0.14. The syntax is identical to PostgreSQL, requiring the LATERAL keyword directly preceding the derived table definition.
MySQL 8.0 lateral derived table example
SELECT d.department_name, top_earners.employee_name, top_earners.salaryFROM departments dJOIN LATERAL ( SELECT e.employee_name, e.salary FROM employees e WHERE e.department_id = d.department_id ORDER BY e.salary DESC LIMIT 2) AS top_earners ON true;
As stated in the MySQL lateral derived tables documentation, a lateral derived table can only reference tables that precede it in the FROM clause, not tables defined later.
Reusing computed expressions with LATERAL
In complex queries with repeated mathematical calculations, you can use CROSS JOIN LATERAL to calculate an expression once and reuse the alias across SELECT, WHERE, and GROUP BY clauses without repeating the formula.
Reusing calculated values via LATERAL
SELECT item_id, calc.gross_margin, calc.tax_amount, calc.final_priceFROM inventory_items iCROSS JOIN LATERAL ( SELECT (i.retail_price - i.wholesale_cost) AS gross_margin, (i.retail_price * 0.08) AS tax_amount, (i.retail_price * 1.08) AS final_price) AS calcWHERE calc.gross_margin > 50.00;
Confirm index support: ensure a composite index exists on (parent_id, sort_column DESC) on the child table.
Choose join type: use LEFT JOIN LATERAL ... ON true to preserve parent rows with zero matching child rows.
Position tables sequentially: verify the referenced parent table appears before the LATERAL subquery in the FROM list.
Evaluate against window functions: benchmark LATERAL against ROW_NUMBER() when filtering parent tables by indexed criteria.
Isolate complex calculations: use CROSS JOIN LATERAL to eliminate duplicate mathematical formulas in reporting queries.
Keep subqueries bounded: always include an explicit LIMIT inside top-N lateral subqueries.
Wrapping up
SQL LATERAL joins provide a clean, expressive way to write correlated subqueries in your FROM clause, enabling index-assisted top-N per group lookups and reusable computed values. Keep your complex multi-table joins and lateral subqueries readable and formatted by using sqlfmt or exploring our Pro plans.