Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In PostgreSQL, the LATERAL keyword is used to reference a column from a table that is used as an input for another table. In other words, it allows a query to reference columns from a table listed earlier in the join clause.

The LATERAL keyword is used in combination with the JOIN keyword, and it can be used with subqueries or functions. It is often used to improve performance by reducing the number of joins required for a query.

For example, consider two tables: employees and departments. If we want to find the name of the department for each employee, we can use a JOIN query like this:

SELECT employees.name, departments.name
FROM employees
JOIN departments
ON employees.department_id = departments.id;

However, if we want to find the names of all employees in all departments, we need to use a subquery or a function to generate a list of all departments. This is where the LATERAL keyword can be useful.

SELECT employees.name, department_names.name
FROM employees
LEFT JOIN LATERAL (SELECT name FROM departments WHERE id = employees.department_id) department_names ON true;

In this example, the subquery is executed once for each row of employees, allowing us to retrieve the name of the department for each employee without using a separate JOIN statement. The LATERAL keyword ensures that the subquery is run for each row in the outer query.