SQL

SQL Left Join full explanation with example

Hi there,

In this post, I will explain, how to use left join in SQL, SQL left join statement returns all rows from the left table and matching rows from the right table.

1-First, we need two input tables that we want to join.

Download the input Data sql commands

Input table 1 (Orders)

OrderID CustomerId Product OrderDate ShipperID
10308 2 Laptop 2021-09-18 3
10309 37 Xbox 2021-09-19 2
10310 77 Laptop 2021-07-07 1

SQL commands

Create table Orders (OrderID varchar(25),  CustomerId int, Product varchar(25), OrderDate date, ShipperID int);

Insert into orders values (‘10308’, 2, ‘Laptop’, ‘2021-09-18’, 3), (‘10309’, 37, ‘Xbox’, ‘2021-09-19’, 2),(‘10310’, 77, ‘Laptop’, ‘2021-07-07’, 1);

Input Table 2 (Customers Table)

Create table Customers (CustomerId int, CustomerName varchar(25), Phone varchar(25), Address varchar(25), City varchar(25), Postalcode int, Country varchar(25));

Insert into Customers values (1, ‘Mohamed Salah’, ‘+2167676’, ‘Sousse Tn 2222’, ‘Sousse’, 2222, ‘Tunisia’), (2, ‘Emna Chachia’, ‘+216879’, ‘Tunis Tn 4444’, ‘Tunis’, 4444, ‘Tunisia’),(3, ‘Souha Mabrouk’, ‘+2167986’, ‘Annaba Algeria 85858’, ‘Annaba’, 85858, ‘Algeria’);

 

CustomerID CustomerName Phone Address City Postalcode Country
1 Mohamed Salah +2167676 Sousse Tn 2222 Sousse 2222 Tunisia
2 Emna Chachia +216879 Tunis Tn 4444 Tunis 4444 Tunisia
3 Souha Mabrouk +2167986 Annaba Algeria 85858 Annaba 85858 Algeria

2- Second, we apply the left join command:

Left Join SQL:

Select * From Orders left join customers on Orders.CustomerId=Customers.CustomerId;

3- Third, we have our result:

Expected result:

Read also:

How to install MySQL on windows

SQL inner Join full explanation with example

How to create a table using SQL and insert values into it

SQL Syntax

 

Related Articles

Leave a Reply

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

Back to top button