SQL LEFT JOIN

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.

 

Syntax:

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

 

Customers table:

customer_id fullname
1 Kailash
2 Amit
3 Siddarth
4 Vikas

Orders table:

order_id amount customer
1 2000 2
2 3000 4
3 3500 5
4 2500 7

 

Here, the SQL command selects customer_id and fullname columns (from the Customers table) and the amount column (from the Orders table).

QUERY:

SELECT Customers.customer_id, Customers.fullname, Orders.amount
FROM Customers
LEFT JOIN Orders
ON Customers.customer_id = Orders.customer;

 

And, the result set will contain those rows where there is a match between customer_id (of the Customers table) and customer (of the Orders table) along with all the remaining rows from the Customers table.

 

Result:

customer_id fullname amount
1 Kailash  
2 Amit 2000
3 Siddarth  
4 Vikas 3000