SQL LEFT JOIN

SQL LEFT JOIN clause is used to select all the matched records from the left side table, regardless if it has matched records in the right side table or not.

SQL LEFT JOIN Clause Syntax

SELECT Table1.Column1, Table1.Column2, ... , Table2.Column1, Table2.Column2, ...
FROM Table1
LEFT JOIN Table2
ON Table1.ColumnName = Table2.ColumnName

SQL LEFT JOIN Clause Example

Table: Employees

EmployeeId FirstName LastName Department Salary
203 Mazojys Fxoj Finance 78000
204 Jozzh Lnanyo Finance 45800
205 Syllauu Dfaafk Finance 57000
206 Gecrrcc Srlkrt Finance 62000

Table: Tickets

TicketID TicketNo EmployeeId
1 2349 203
2 2400 204
3 2438 205

Select all the employees, if they have any tickets, list the tickets:

SELECT Employees.EmployeeId
           , Employees.FirstName
           , Employees.LastName
           , Tickets.TicketNo
FROM Employees
LEFT JOIN Tickets
ON Employees.EmployeeId = Tickets.EmployeeId

The result will look like:

EmployeeId FirstName LastName TicketNo
203 Mazojys Fxoj 2349
204 Jozzh Lnanyo 2400
205 Syllauu Dfaafk 2438
206 Gecrrcc Srlkrt

Note: The employee whose EmployeeId is 206 doesn’t have any records matched in the table Tickets, but he is still listed in the result with the TicketNo null.

4 Responses to SQL LEFT JOIN

  1. Nice article about left join with good example); good to see such kinds of article
    eGrove Systems recently posted..Welcome to BEST PMO

  2. FettesPS says:

    It’s amazing how many programmers dont know their joins. I’d say 99% never use anything more than an inner join :(

  3. SQL Tutor says:

    I agree left / right joins are very important but seldom used. Not relevant in some situation but when they are called for they do a much better job than inner joins. I guess people simply don’t know that they exist, and how they work.
    Nice tutorial.

  4. Daycare says:

    I use left joins all the time. Couldn’t imagine “life” without them :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv Enabled