The basic syntax of a LEFT JOIN
is:
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
table1
, table2
: The two tables to join.column
: The column(s) used to match rows in both tables.Let’s assume we have two tables: employees
and departments
. We want to retrieve all employees and their corresponding department names. If an employee does not belong to a department, the department name will show as NULL
. Here’s the query:
SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id;
In this example:
employees
table.department_id
from the employees
table with the id
in the departments
table.department_name
will be NULL
.NULL
for columns from the right table.The LEFT JOIN
is a useful tool when you need to include all records from the left table, even if there are no matching records in the right table. It’s essential for situations where you want to ensure that all rows from the left table are included, with NULL
placeholders for missing data from the right table. Using LEFT JOIN
helps in retrieving comprehensive data across related tables, especially when some relationships may be missing.