SQL

SQL RIGHT JOIN With Examples

SQL Right Join

The SQL RIGHT JOIN returns all rows from the right table. Suppose there are no matches in the left table then also the join will still return a row in the result.

This means that a right join returns all the values from the right table, plus matched values from the left table or NULL in case of no match.

SQL RIGHT JOIN Avtartime

Syntax:

SELECT column_names
FROM table_name_1
RIGHT 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
RIGHT 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 |
+--------------+-----------+--------+

For more joins, you can check here.

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

Also Read  SQL INNER JOIN With Examples

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