⬅ Previous Topic
SQL RIGHT JOINNext Topic ⮕
SQL SELF JOIN⬅ Previous Topic
SQL RIGHT JOINNext Topic ⮕
SQL SELF JOINImagine you have a list of students and a separate list of exam results. Some students didn’t appear. Some results don’t have a matching student. You want a complete view — no exclusions. That’s what FULL OUTER JOIN
does. It combines all rows from both tables, matched or not.
FULL OUTER JOIN
returns:
SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.common_column = table2.common_column;
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10)
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', '10A'),
(2, 'Diya Iyer', '9B'),
(3, 'Sneha Patil', '10A'),
(4, 'Mehul Agarwal', '8C');
CREATE TABLE results (
roll_no INT,
subject VARCHAR(30),
marks INT
);
INSERT INTO results VALUES
(1, 'Maths', 85),
(2, 'Maths', 92),
(5, 'Maths', 88); -- No student with roll_no 5
Let’s see all students and all results, matched or not:
SELECT s.roll_no AS student_roll,
s.name AS student_name,
r.subject,
r.marks
FROM students s
FULL OUTER JOIN results r
ON s.roll_no = r.roll_no;
student_roll | student_name | subject | marks
-------------+----------------+---------+-------
1 | Aarav Sharma | Maths | 85
2 | Diya Iyer | Maths | 92
3 | Sneha Patil | NULL | NULL
4 | Mehul Agarwal | NULL | NULL
NULL | NULL | Maths | 88
Explanation: You see:
Want to find only mismatches (unmatched records)?
SELECT s.name, r.subject, r.marks
FROM students s
FULL OUTER JOIN results r ON s.roll_no = r.roll_no
WHERE s.roll_no IS NULL OR r.roll_no IS NULL;
name | subject | marks
----------------+---------+-------
NULL | Maths | 88
Sneha Patil | NULL | NULL
Mehul Agarwal | NULL | NULL
Some databases (like MySQL) don’t support FULL OUTER JOIN
directly. You can simulate it using UNION
of LEFT JOIN
and RIGHT JOIN
:
SELECT s.roll_no, s.name, r.subject, r.marks
FROM students s
LEFT JOIN results r ON s.roll_no = r.roll_no
UNION
SELECT s.roll_no, s.name, r.subject, r.marks
FROM students s
RIGHT JOIN results r ON s.roll_no = r.roll_no;
FULL OUTER JOIN
gives you the big picture. Whether you're building a report card, checking attendance logs, or reconciling financial data — this join shows everything: the perfect matches, and the missing pieces.
Now that you know all join types, we’ll explore SELF JOIN — joining a table with itself to uncover patterns within a single dataset.
SELECT s.name, sp.event FROM students s FULL OUTER JOIN sports_participation sp ON s.roll_no = sp.roll_no;
⬅ Previous Topic
SQL RIGHT JOINNext Topic ⮕
SQL SELF JOINYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.