Question presented to candidate: "What does the LATERAL keyword do in a FROM clause? Show me a query that needs it, and tell me how it differs from a normal join to a subquery."
What a strong answer should cover:
- A normal derived table in FROM cannot reference other tables of the same FROM clause;
LATERALlets it reference items to its left - Semantics: the lateral subquery is evaluated once per row of the left side, like a correlated subquery that can return many rows and many columns
CROSS JOIN LATERALdrops left rows with no result;LEFT JOIN LATERAL ... ON truekeeps them with NULLs- Typical uses: top-N / latest-row per group with
ORDER BY ... LIMIT, several columns from one lookup, reusing a computed expression, set-returning functions (implicitly lateral) - Plans: usually a Nested Loop that runs the inner side once per outer row, fast when an index serves the inner lookup
- Engine support: PostgreSQL and MySQL 8.0.14+ spell it
LATERAL, SQL Server usesCROSS APPLY/OUTER APPLY, SQLite has noLATERAL
Code / implementation expected: Yes β a LATERAL subquery that returns each customer's latest order, and the LEFT JOIN LATERAL variant.
Schema used by the examples: