MySQL Full Outer Join

In MySQL, a full outer join, also known as a full join or full outer join, combines all rows from both the left and right tables based on a related column between them, and returns NULL for the columns where there is no matching row in either table. The basic syntax for a full outer join in MySQL is:

SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.column = table2.column;

However, MySQL does not have a built-in full outer join syntax. To achieve a full outer join in MySQL, we can use a combination of left and right joins with the UNION operator. Here’s an example:

SELECT orders.order_id, customers.customer_name
FROM orders
LEFT JOIN customers
ON orders.customer_id = customers.customer_id
UNION
SELECT orders.order_id, customers.customer_name
FROM orders
RIGHT JOIN customers
ON orders.customer_id = customers.customer_id
WHERE orders.customer_id IS NULL;

In this example, we first perform a left join between the orders table and the customers table, which returns all orders and matching customer names. We then perform a right join between the same tables, but filter out any rows where there is a matching order ID, which returns all customers without a matching order ID. Finally, we combine the two results using the UNION operator to get a full outer join result.

For example, consider two tables, employees and departments, where the departments table has a column dept_id that relates to the employees table’s column dept_id. We can use a full outer join to get all the employees and departments, along with their corresponding department or employee names.

SELECT employees.employee_name, departments.department_name
FROM employees
LEFT JOIN departments
ON employees.dept_id = departments.dept_id
UNION
SELECT employees.employee_name, departments.department_name
FROM employees
RIGHT JOIN departments
ON employees.dept_id = departments.dept_id
WHERE employees.employee_name IS NULL;
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial