Left Join in SQL

SQL

A LEFT JOIN statement in SQL is used to retrieve records from two or more tables based on a related column, and it includes all records from the left table along with the matched records from the right table.

If there are no matching records in the right table, NULL values are included in the result set for columns from the right table.

Syntax:

SELECT *
FROM left_table
LEFT JOIN right_table ON left_table.column_name = right_table.column_name;
  • Explanation:
    • left_table: The table from which you want to retrieve all records.
    • right_table: The table you want to join with the left table.
    • column_name: The column used to establish the relationship between the two tables.

Example:

Consider two tables, employees and departments:

Table: employees

emp_idemp_nameemp_dept_idemp_salary
1John10150000
2Mary10260000
3Bob10155000

Table: departments

dept_iddept_name
101IT
102Finance
103Marketing

Table: projects

project_idproject_nameemp_id
1Project A1
2Project B2
3Project C3

Simple LEFT JOIN

Let’s aim to retrieve all employees and their corresponding departments, even if some employees don’t have assigned departments.

SELECT *
FROM employees
LEFT JOIN departments ON employees.emp_dept_id = departments.dept_id;

Output:

emp_idemp_nameemp_dept_idemp_salarydept_iddept_name
1John10150000101IT
2Mary10260000102Finance
3Bob10155000101IT
4Alice10352000NULLNULL

LEFT JOIN with WHERE Clause

SELECT *
FROM employees
LEFT JOIN departments ON employees.emp_dept_id = departments.dept_id
WHERE employees.emp_salary > 55000;

Output:

emp_idemp_nameemp_dept_idemp_salarydept_iddept_name
2Mary10260000102Finance

Handling NULL Values

Understanding how NULL values are handled in a LEFT JOIN scenario.

SELECT emp_name, dept_name
FROM employees
LEFT JOIN departments ON employees.emp_dept_id = departments.dept_id;

Output:

emp_namedept_name
JohnIT
MaryFinance
BobIT
AliceNULL

LEFT JOIN with Multiple Tables:

Retrieve information about employees, their departments, and the projects they are working on.

SELECT *
FROM employees
LEFT JOIN departments ON employees.emp_dept_id = departments.dept_id
LEFT JOIN projects ON employees.emp_id = projects.emp_id;

Output:

emp_idemp_nameemp_dept_idemp_salarydept_iddept_nameproject_idproject_name
1John10150000101IT1Project A
2Mary10260000102Finance2Project B
3Bob10155000101IT3Project C

LEFT JOIN with Aggregation:

Calculate the average salary of employees in each department, including those without projects.

SELECT departments.dept_id, departments.dept_name, AVG(employees.emp_salary) as avg_salary
FROM departments
LEFT JOIN employees ON departments.dept_id = employees.emp_dept_id
GROUP BY departments.dept_id, departments.dept_name;

Output:

dept_iddept_nameavg_salary
101IT52500
102Finance60000
103MarketingNULL

Read more about Join