LATERAL turns an otherwise isolated derived table into a correlated one. When you prefix a subquery, table function, or VALUES list with LATERAL inside the FROM clause, the SQL engine evaluates it once per row produced by the tables that appear to its left. Inside the LATERAL subquery you can therefore use columns from those preceding tables, just like in a correlated subquery in the WHERE clause, but with the power to return a full result set that can be joined, filtered, or aggregated.Key behaviors:- Scope: Only columns from tables that come before the LATERAL item are visible; later tables are not.- Execution order: For each row of the left-hand table(s), the LATERAL subquery is executed, similar to a nested-loops join.- Join types: You can pair LATERAL with CROSS JOIN, INNER JOIN, LEFT JOIN, or simply place it as a comma-separated item (which is equivalent to CROSS JOIN LATERAL).- Performance: Since the subquery runs per row, heavy logic can be expensive. Indexing and limiting rows on the left side are important.- ANSI SQL: LATERAL is part of SQL:2011. SQL Server and older MySQL versions lack the reserved word but offer equivalent APPLY or correlated derived tables.
CROSS JOIN LATERAL, APPLY, correlated subquery, set-returning functions, JSON processing, table functions
PostgreSQL 9.3, SQL:2011 standard
It lets you join each row to a custom, possibly multi-row result generated by a subquery or function that can see that row's values. This eliminates workarounds like self joins or repeated correlated subqueries.
CROSS JOIN LATERAL (or simply placing the LATERAL item without an ON clause) keeps only rows that produce at least one match. INNER JOIN LATERAL lets you add an ON filter. LEFT JOIN LATERAL preserves all left-hand rows even when the subquery returns no rows.
Yes, unless your database infers it by default (PostgreSQL requires the keyword). In SQL Server you use APPLY instead; in Oracle you can omit LATERAL with table functions.
Yes. Each LATERAL subquery can see columns from all tables before it, so you can build step-by-step derived tables while keeping the query readable.