Facebook Page Twitter Page LinkedIn Page
× SQL Tutorial SQL Advanced SQL Database SQL Resources


The SQL LEFT JOIN keyword is used to combine column values of two tables based on the match between the columns. It returns all rows of the table on the left side of the join and matching rows of the table on the right side of the join. The rows of the left side table where there is no match in the right side table, the result table will contain NULL value.

SQL LEFT JOIN

Syntax

The syntax for using LEFT JOIN keyword is given below:

SELECT table1.column1, table1.column2, table2.column1, table2.column2, ...
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Example:

Consider database tables called Employee and Contact_Info with the following records:

Table 1: Employee table

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

Table 2: Contact_Info table

Phone_NumberEmpIDAddressGender
+1-80XXXXX0002XXX, Brooklyn, New York, USAF
+33-14XXXXX013XXX, Grenelle, Paris, FranceM
+31-20XXXXX194XXX, Geuzenveld, Amsterdam, NetherlandsF
+86-10XXXXX4586XXX, Yizhuangzhen, Beijing, ChinaM
+65-67XXXXX47XXX, Yishun, SingaporeM
+81-35XXXXX728XXX, Koto City, Tokyo, JapanM

  • To left join Employee and Contact_Info tables based on matching column EmpID, the SQL code is given below. This will fetch Name and Age columns from Employee table and Address column from Contact_Info table.

    SELECT Employee.Name, Employee.Age, Contact_Info.Address 
    FROM Employee
    LEFT JOIN Contact_Info
    ON Employee.EmpID = Contact_Info.EmpID;
    

    This will produce the result as shown below:

    NameAgeAddress
    John25
    Marry24XXX, Brooklyn, New York, USA
    Jo27XXX, Grenelle, Paris, France
    Kim30XXX, Geuzenveld, Amsterdam, Netherlands
    Ramesh28
    Huang28XXX, Yizhuangzhen, Beijing, China
  • To fetch all fields of a table, table.* keyword is used, for example - to fetch all fields of the Employee table, Employee.* is used in the below SQL code:

    SELECT Employee.*, Contact_Info.Address 
    FROM Employee
    LEFT JOIN Contact_Info
    ON Employee.EmpID = Contact_Info.EmpID;
    

    This result of the following code will be:

    EmpIDNameCityAgeSalaryAddress
    1JohnLondon253000
    2MarryNew York242750XXX, Brooklyn, New York, USA
    3JoParis272800XXX, Grenelle, Paris, France
    4KimAmsterdam303100XXX, Geuzenveld, Amsterdam, Netherlands
    5RameshNew Delhi283000
    6HuangBeijing282800XXX, Yizhuangzhen, Beijing, China


Recommended Pages


5