Of Zen and Computing

How to do a Left Join in SQL

Digg icon StumbleUpon icon del.icio.us icon Facebook icon

A left join is a table join in which all of the matched records from the table on the left side of the join are returned, regardless of whether a matching record is found in the table on the right side of the join.

To illustrate the workings of a left join, let’s consider two tables representing employees and departments within a fictional company.

Table: employees

EmpIdDeptIdEmpFirstNameEmpLastName
13JohnDoe
21JaneDoe
32JimSmith
4nullJoeSchmoe

Table: departments

DeptIdDepartment
1Human Resources
2Accounting
3Information Technology

The Situation

Here’s a situation that would require a left join: design a query that produces a list of all employees, including which department, if any, each employee works for.

Joe Schmoe is the monkey wrench in this case. He doesn’t work for any department, but he must be included in the results of our query. A regular join would exclude Joe from the results — but a left join would do the trick.

The Code

SELECT
    employees.EmpFirstName,
    employees.EmpLastName, 
    departments.Department
FROM 
    employees
LEFT JOIN departments
    ON employees.DeptId = departments.DeptId

The Output

EmpFirstNameEmpLastNameDepartment
JohnDoeInformation Technology
JaneDoeHuman Resources
JimSmithAccounting
JoeSchmoenull

File under: Code

Other articles related to this page

1 response

  1. Thanks alot. This explanation was easy to understand and very helpful.

Leave a Comment

RSS Feed Icon comment feed