A lateral join in SQL is a special type of join that allows a subquery in the FROM clause to refer to columns from the preceding tables in the same FROM clause. It essentially enables you to run a correlated subquery for each row from the outer query. This means that, for every row processed from the outer table, the subquery can access values from that row, effectively treating it as if it is "lateral" to the other rows in the outer query. The syntax for lateral joins often involves the keyword LATERAL
, which defines the scope of the subquery in relation to the outer query.
To illustrate how a lateral join works, consider an example with two tables: employees
and projects
. Suppose you want to list each employee along with their most recent project. You could write a query where the main part selects from the employees
table, and the lateral subquery retrieves the most recent project for each employee by using a condition that accesses the employee's ID. The lateral join allows the subquery to consider each employee's details in determining which project to return.
Using the LATERAL
keyword, the SQL query would look something like this:
SELECT e.name, p.project_name
FROM employees e
CROSS JOIN LATERAL (
SELECT project_name
FROM projects
WHERE projects.employee_id = e.id
ORDER BY start_date DESC
LIMIT 1
) p;
In this query, for each employee, the subquery fetches the latest project based on the start_date
, ensuring the relationship between the tables is properly maintained. By using a lateral join, you can efficiently co-relate the main and subquery data, leading to more readable and maintainable SQL queries.