LATERAL
LATERAL is an SQL clause used in conjunction with a subquery in the FROM clause. The LATERAL keyword allows the subquery to refer to columns of preceding tables in the FROM clause. Contrary to standard subqueries, which are independent and executed first, a LATERAL subquery is reevaluated for each row in the outer query, thereby allowing for complex, row-dependent operations.
Example
Output
Explanation
In the specified SQL query, LATERAL is used to allow subquery in FROM clause to refer to columns of preceding FROM items. The query returns a table with columns product and sale. Here, sale
is a sum of quantities for each product from the sales table where the product_id matches between the sales and products tables.
Example
Output
Explanation
In the given SQL Server example, the OUTER APPLY
clause (equivalent to the standard SQL keyword LATERAL
) allows each row in the Person
table to be used in the subquery to obtain the most recent SalesOrderHeader
for that specific person
. It functions similarly to a more dynamic JOIN
clause, where each row in the left table (Person
) can be utilized in a correlated subquery with the right table (SalesOrderHeader
).
Example
Output
Explanation
This SQL snippet applies the LATERAL join clause to interrelate rows from table_A with those of table_B using a shared column_name.LATERAL
allows a subquery in the FROM clause to refer to columns in preceding items in the FROM list. In this example, it enables the subquery to access values in the table_A within its scope.