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.