Of Zen and Computing

How to do a Left Join in SQL

Wednesday, February 27, 2008

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

Categories: Code

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

Other articles related to this page

© 2006-2009 OfZenAndComputing.com
E-mail Disclaimer | Terms of Service & Disclaimer | Sitemap

Subscription Options
Search Our Archive of How-To Articles and Blog Posts