In this article we will see "How to use RIGHT JOIN in MySql" and "RIGHT JOIN query syntax with example".

A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

RIGHT JOIN query in MySql syntax

RIGHT JOIN returns all records from the right table, and the matched records from the left table. The result is NULL from the left side, if there is no match, syntax is as follows.


SELECT columnName(s)
FROM table1
RIGHT JOIN table2 ON table1.columnName = table2.columnName;


RIGHT JOIN query in MySql example

Let's assume we have following two tables, 'EMPLOYEE' and 'DEPARTMENT' as shown below:


/*EMPLOYEE table */
+----+--------+---------+
| id | name   | email   |
+----+--------+---------+
|  1 | name-1 | email-1 |
|  2 | name-2 | email-2 |
|  3 | name-3 | email-3 |
|  4 | name-4 | email-4 |
+----+--------+---------+

/*DEPARTMENT table */
+----+-------+-------------+
| id | name  | EMPLOYEE_ID |
+----+-------+-------------+
|  1 | DEP-1 |           1 |
|  2 | DEP-1 |           2 |
|  3 | DEP-2 |           2 |
|  4 | DEP-2 |           1 |
+----+-------+-------------+



We will now apply RIGHT JOIN on above two table to see the result, based on condition as shown below:


SELECT e.name EMPLOYEE_NAME, e.email EMPLOYEE_EMAIL, d.name DEPARTMEN_NAME FROM EMPLOYEE e RIGHT JOIN DEPARTMENT d on e.id = d.EMPLOYEE_ID;

Output: Output will be something like this:


+---------------+----------------+----------------+
| EMPLOYEE_NAME | EMPLOYEE_EMAIL | DEPARTMEN_NAME |
+---------------+----------------+----------------+
| name-1        | email-1        | DEP-1          |
| name-2        | email-2        | DEP-1          |
| name-2        | email-2        | DEP-2          |
| name-1        | email-1        | DEP-2          |
+---------------+----------------+----------------+


In this article we have seen "How to use RIGHT JOIN in MySql" and "RIGHT JOIN query syntax with example", in upcoming articles we will see more about Mysql syntax and queries with example.
  • By Techburps.com
  • Oct 20, 2017
  • MySql