Open In App

Understanding LATERAL Joins in PostgreSQL

Last Updated : 04 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

LATERAL joins in PostgreSQL are an advanced join technique that allows subqueries to reference columns from tables that appear earlier in the FROM clause of a query. This unique functionality makes it possible to write dynamic subqueries that rely on data from preceding tables, allowing for greater flexibility in complex queries.

In this article, we’ll cover the definition, syntax, and several examples to help us understand how and when to use LATERAL joins effectively. Additionally, we’ll explore correlated subqueries, and compare LATERAL joins with other types of joins.

What are LATERAL Joins in PostgreSQL?

A LATERAL join is a type of join that allows a subquery to reference columns from preceding tables in the FROM clause of a SQL query. This means the subquery can refer to the rows from previous tables when generating its results. This flexibility helps simplify complex queries and improve their efficiency by reducing repetitive code and making the queries more readable.

Syntax:

SELECT columns
FROM table1
JOIN LATERAL subquery AS alias ON condition;

Key Terms:

  • main_table represents the table we are querying first.
  • LATERAL allows the subquery to reference columns from main_table.
  • alias gives a name to the result of the subquery for use in the SELECT statement.
  • join_condition specifies how the main table and the subquery’s result should relate.

Setting Up the Environment for LATERAL Join Examples

To demonstrate LATERAL joins, we’ll create two tables: departments for department details and employees for employee information. Then, we’ll insert sample data and explore LATERAL join examples in PostgreSQL.

Step 1: Create Tables

We will create two tables: departments for department details and employees for employee information.

Query:

CREATE TABLE departments (
id SERIAL PRIMARY KEY,
department_name VARCHAR(50)
);

CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
salary NUMERIC(10, 2),
department_id INT REFERENCES departments(id)
);

Step 2: Insert Sample Data

Next, let’s add some sample data to these tables for demonstration purposes:

Query:

INSERT INTO departments (department_name) VALUES
('Human Resources'),
('Engineering'),
('Sales');

INSERT INTO employees (name, salary, department_id) VALUES
('Alice', 60000, 1),
('Bob', 75000, 2),
('Charlie', 50000, 2),
('Diana', 65000, 1),
('Ethan', 70000, 3);

Now we have some data, by using these we will understand LATERAL joins in PostgreSQL.

Examples for LATERAL Joins in PostgreSQL

Here table1 is the main table. Subquery is the nested query that can use information from table1. Alias is a name we give to the result of the subquery. Condition tells how to join the tables together.

Example 1: Simple LATERAL Join to Calculate Average Salary per Department

Suppose we want to list each employee along with the average salary of their department. We can accomplish this with a LATERAL join that calculates the department’s average salary using data from the employees table.

Query:

SELECT e.name, d.avg_salary
FROM employees e
JOIN LATERAL (
SELECT AVG(salary) AS avg_salary
FROM employees
WHERE department_id = e.department_id
) d ON true;

Output

output1
Output1

Explanation:

  • We select the employee's name from the employees table.
  • The LATERAL subquery calculates the average salary for employees in the same department as the current employee.
  • The ON true condition means we include all rows from the employees table.

Example 2: LATERAL Join with Complex Queries to Count Employees per Department

Now, we will se a more complex example where we want to list departments with their employees and the total number of employees in each department.

Query:

SELECT d.department_name, emp_count.name, emp_count.total_employees
FROM departments d
JOIN LATERAL (
SELECT e.name, COUNT(*) OVER() AS total_employees
FROM employees e
WHERE e.department_id = d.id
) emp_count ON true;

Output

output2
Output2

Explanation:

  • We select the department name from the departments table.
  • The LATERAL subquery gets each employee's name and counts the total number of employees in that department.
  • The result shows each department along with its employees and the total number of employees.

Correlated Subquery and LATERAL Joins

A correlated subquery refers to columns from a previous table which makes it dependent on the row-by-row data from the main query. LATERAL joins are well-suited for correlated subqueries because they allow a subquery to use values from the outer query's rows.

Example of Correlated Subquery with LATERAL Join

Now, we will see an example to clearly understand it. Here if we want to retrieve a department's name along with a list of employees and the total employee count for that department.

Query:

SELECT d.department_name, emp_details.name, emp_details.total_employees
FROM departments d
JOIN LATERAL (
SELECT e.name, COUNT(*) OVER() AS total_employees
FROM employees e
WHERE e.department_id = d.id
) emp_details ON true;

Output

output3
Output3

Explanation:

  • departments table rows are processed one by one.
  • For each dept. , the LATERAL subquery finds the names and counts of employees in that department.
  • COUNT(*) OVER() computes the total count for each department in one step.

Differences: LATERAL Join vs Other Joins

LATERAL JOIN vs INNER JOIN

  • INNER JOIN: Returns rows that meet a specified condition in both tables.
  • LATERAL JOIN: Allows subqueries to access columns from tables that come before it in the query, supporting correlated subqueries. Inner joins don’t directly support correlated subqueries.

LATERAL JOIN vs LEFT JOIN

  • LEFT JOIN: Returns all records from the left table, even if there are no matches in the right table.
  • LATERAL JOIN: Evaluates a subquery for each row in the preceding table, making it possible to show different results for each row based on main table data.

Unique Feature: Unlike Inner join or Left Join, the LATERAL keyword allows the subquery to depend on preceding tables. This access to previous table rows help it to enable dynamic computations.

Conclusion

In this article, we explored LATERAL joins in PostgreSQL, including their syntax, examples, and unique ability to access values from preceding tables within a subquery. We covered correlated subqueries, examined how LATERAL joins simplify complex queries, and highlighted differences between LATERAL and other types of joins. By using LATERAL joins, we can make our SQL queries more flexible and efficient, especially when we need dynamic subqueries based on prior data in the same query.


Next Article
Article Tags :

Similar Reads