SQL

SQL LEFT JOIN With Examples

SQL LEFT JOIN:

The SQL LEFT JOIN will return all the rows from the left table also it returns the null value in the column where it does not match value from the right table.

SQL LEFT JOIN Avtartime

Syntax:

SELECT column_names
FROM table_name_1
LEFT JOIN table_name_2 ON table_name_1.column_name = table_name_2.column_name;

For example, just see below and try to understand

Table -1 CUSTOMERS Table is as follows. Here we are taking 5 records with 3 columns as (CustomerId, CustomerName, and CustomerAge)

+------------+--------------+-------------+
| CustomerId | CustomerName | CustomerAge |
+------------+--------------+-------------+
|          1 | John         |          25 |
|          2 | Smith        |          27 |
|          3 | Lulia        |          32 |
|          4 | Kristin      |          26 |
|          5 | Martin       |          22 |
+------------+--------------+-------------+

 Table -2  Orders Table is as follows. Here we are taking 4 records with 4 columns as (OrderId, OrderName, CustomerId, and Amount)

+---------+-----------+------------+--------+
| OrderId | OrderName | CustomerId | Amount |
+---------+-----------+------------+--------+
|       1 | Pizza     |          2 |    150 |
|       2 | Burger    |          2 |     50 |
|       3 | Noddle    |          4 |     30 |
|       4 | Ice Cream |          5 |     20 |
+---------+-----------+------------+--------+
SELECT customers.CustomerName,orders.OrderName,orders.Amount
FROM customers
LEFT JOIN orders on orders.CustomerId=customers.CustomerId

As a result for above query

+--------------+-----------+--------+
| CustomerName | OrderName | Amount |
+--------------+-----------+--------+
| Smith        | Pizza     |    150 |
| Smith        | Burger    |     50 |
| Kristin      | Noddle    |     30 |
| Martin       | Ice Cream |     20 |
| John         | NULL      |   NULL |
| Lulia        | NULL      |   NULL |
+--------------+-----------+--------+

For more joins, you can check here.

Sign Up for getting more new articles directly in your mail Inbox. 

Also Read  SQL Joins With Examples (Inner Join, Left Join, Right Join, Full Join, Self Join)

About the author

Avtar

I am a blogger and I always believes in sharing a knowledge and happiness because happiness is the last journey of life.

Leave a Comment

Share
Tweet
Pin
+1
Share
0 Shares