SQL Joins
SQL LEFT JOIN
Left Outer Join in SQL
LEFT OUTER JOIN includes all rows from the left table, with NULLs for non-matching right table rows.
What is SQL LEFT JOIN?
The SQL LEFT JOIN clause is used to combine rows from two or more tables. It returns all the rows from the left table and the matched rows from the right table. If there is no match, the result is NULL on the side of the right table.
Syntax of LEFT JOIN
The basic syntax of a LEFT JOIN is as follows:
Example of LEFT JOIN
Let's consider two tables: Employees
and Departments
.
The Employees
table includes:
- EmployeeID: Unique identifier for each employee
- Name: Name of the employee
- DepartmentID: Identifier for the department the employee belongs to
The Departments
table includes:
- DepartmentID: Unique identifier for each department
- DepartmentName: Name of the department
Here is an example query that uses LEFT JOIN to list all employees and their respective departments:
This query will return all rows from the Employees
table. If an employee's department does not exist in the Departments
table, the DepartmentName
will be NULL
.
When to Use LEFT JOIN
Use LEFT JOIN when you want to ensure that all data from the left table appears in your result set, regardless of whether there is a matching record in the right table. This is particularly useful when you need a complete list of records from one table and only related records from another.
Performance Considerations
While LEFT JOINs are powerful, they can also affect performance, especially with large datasets. It's important to ensure that your join conditions are indexed properly to avoid slow query execution.
SQL Joins
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- FULL JOIN
- CROSS JOIN
- Self Join
- Previous
- INNER JOIN
- Next
- RIGHT JOIN