LEFT JOIN
Overview
The LEFT JOIN
returns all matching records from the left table combined with the right table. Even if there are no matching records in the right table, the LEFT JOIN
will still return a row in the result, but with NULL in each column from the right table.
LEFT JOIN
is also known as LEFT OUTER JOIN
.Syntax
LEFT JOIN
clause.a) Basic Syntax
In the above syntax:
-
SELECT column_1, column_2...
defines the columns from both tables where we want the data to be selected. -
FROM table_1
defines the left table as the main table in the FORM clause. -
RIGHT JOIN table_2
defines the right table as the table the main table joins. -
ON table_1.matching_field = table2.matching_field
sets the join condition after the ON keyword with the matching field between the two tables.
b) Syntax with an Alias
You can use an alias to refer to the table’s name. The results will stay the same. It only helps to write the query easier.
Example
item table
It will create a table as shown below:
invoice table
It will create a table as shown below:
1) Based on the above tables, we can write a LEFT JOIN
query as follows:
-
The item = left table, and the invoice = right table.
-
Then it combines the values from the item table using the item_no and matches the records using the item column of each row from the invoice table.
-
If the records are equal, a new row will be created with
item_no
,item_name
, andsold_qty
,sold_price
columns as defined in theSELECT
clause. -
ELSE it will create a new row with a
NULL
value from the right table (invoice).
2) The above query will give the following result:
Based on the data from the item and invoice tables:
-
The result matches the total item stored in the item table: 4 items.
-
The result will display all the item’s data from the left table (item table), even if there is 1 item that hasn’t been sold.
-
The item id:
111
matches the itembutter
and has been sold for 3pcs/9000. -
The item id:
113
matches the itemtea
but has never been sold. Thus the sold_qty & sold_price columns are filled with: null. -
The item id:
116
matches the itemBread
and has been sold three times, for 6pcs/3000, 2pcs/10000, and 1pc/5000. -
The item id:
119
matches the itemCoffee
and has been sold two times, for 5pcs/20000 and 4pcs/16000.
The following Venn diagram illustrates the LEFT JOIN
: