SQL FULL OUTER JOIN: Syntax & Emulating in MySQL via UNION

The FULL OUTER JOIN (or FULL JOIN) produces the complete union of both tables. It returns all rows from the left table and all rows from the right table. Where rows match on the join key, columns are combined; where they do not match, NULL is inserted for whichever side is missing a match.


1. Standard ANSI Syntax (PostgreSQL / SQL Server / Oracle)

SELECT s.first_name, d.dept_name
FROM students s
FULL OUTER JOIN departments d ON s.dept_id = d.dept_id;
student_id first_name dept_name
1 Aman Engineering
2 Pooja Business
3 Rohan Engineering
4 Vikram NULL (unassigned student)
NULL NULL Arts (empty department)

2. Emulating FULL OUTER JOIN in MySQL using UNION

Because MySQL lacks a native FULL JOIN keyword, developers combine a LEFT JOIN and a RIGHT JOIN using UNION (which automatically dedupes overlapping inner-joined rows):

-- MySQL Full Outer Join Emulation:
SELECT s.first_name, d.dept_name
FROM students s
LEFT JOIN departments d ON s.dept_id = d.dept_id

UNION

SELECT s.first_name, d.dept_name
FROM students s
RIGHT JOIN departments d ON s.dept_id = d.dept_id;

Next, let us explore Cartesian matrices and hierarchical queries using SQL CROSS JOIN & SELF JOIN!

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!