In this article we will see "How to use LEFT JOIN in MySql" and "LEFT 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.

LEFT JOIN query in MySql syntax

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


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


LEFT 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 LEFT 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 LEFT 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-1        | email-1        | DEP-2          |
| name-2        | email-2        | DEP-1          |
| name-2        | email-2        | DEP-2          |
| name-3        | email-3        | NULL           |
| name-4        | email-4        | NULL           |
+---------------+----------------+----------------+


In this article we have seen "How to use LEFT JOIN in MySql" and "LEFT 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