Sub topic 2
RIGHT OUTER JOIN and why it mirrors LEFT
This chapter assumes you know basic SELECT, FROM and WHERE syntax, primary and foreign keys, how NULL behaves in SQL, and INNER JOIN with an ON condition. It uses the customers and orders tables from earlier in the tutorial. Order 104 has no customer, and Cleo has no orders.
RIGHT OUTER JOIN
A RIGHT OUTER JOIN (written RIGHT JOIN) keeps every row from the table on its right, even when no row on the left matches. Unmatched left-side columns return as NULL.
SELECT c.name, o.order_id, o.total
FROM customers c
RIGHT JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101 50.00
-- Ada 102 20.00
-- Ben 103 35.00
-- NULL 104 15.00A RIGHT JOIN is a LEFT JOIN with the table order swapped. This query returns the same rows:
SELECT c.name, o.order_id, o.total
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id;Many teams write only LEFT JOINs so that the preserved table always comes first.
Finding rows with no match
Add a WHERE condition that tests a NOT NULL column from the unmatched side for NULL. The query below returns only customers with no orders.
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
-- CleoYou can express the same intent with NOT EXISTS:
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);Filtering in ON versus WHERE
A condition in the ON clause decides which rows can match. A condition in WHERE runs after the join and can remove NULL-padded rows.
-- Filter in WHERE: Cleo is removed
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.total > 30;
-- Ada 101
-- Ben 103
-- Filter in ON: Cleo is kept with NULL
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id AND o.total > 30;
-- Ada 101
-- Ben 103
-- Cleo NULLFULL OUTER JOIN
A FULL OUTER JOIN keeps unmatched rows from both tables. Each side's missing columns are NULL.
SELECT c.name, o.order_id
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101
-- Ada 102
-- Ben 103
-- Cleo NULL
-- NULL 104MySQL does not support FULL OUTER JOIN. PostgreSQL, SQL Server and Oracle do.
Exercise
How many rows does this query return? SELECT c.name, o.orderid FROM customers c FULL OUTER JOIN orders o ON o.customerid = c.customerid WHERE o.orderid IS NULL;
Show answer
One row, Cleo with a NULL orderid. Order 104 has an orderid, so the filter removes it.