Self Joins, UNION and Set Operations
Beyond INNER and LEFT joins, you'll sometimes need to find rows with no match (customers who never ordered), join a table to itself (employees and their managers), or stack results from two queries. These patterns cover most remaining real-world questions.
Self join: a table joined to itself
Give the same table two aliases. Here we find pairs of customers from the same city:
Example
SELECT a.name AS customer, b.name AS same_city_as, a.city
FROM customers a
JOIN customers b ON a.city = b.city AND a.id < b.id;
-- Result:
-- customer | same_city_as | city
-- -----------+--------------+------
-- Asha Verma | Arjun Mehta | Delhi▶ Try it yourselfa.id < b.id stops a customer matching themselves and shows each pair only once.
UNION: stack results
UNION puts the rows of two queries one under the other and removes duplicates. UNION ALL keeps duplicates (and is faster). Both queries must have the same number of columns.
Example
SELECT name, 'customer' AS type FROM customers WHERE city = 'Delhi'
UNION
SELECT name, 'product' FROM products WHERE price > 3000;
-- Result:
-- name | type
-- ------------+---------
-- Arjun Mehta | customer
-- Asha Verma | customer
-- Smart Watch | product▶ Try it yourselfINTERSECT and EXCEPT
Example
-- customers who ordered in October AND in November
SELECT customer_id FROM orders WHERE order_date LIKE '2026-10%'
INTERSECT
SELECT customer_id FROM orders WHERE order_date LIKE '2026-11%';
-- Result:
-- customer_id
-- -----------
-- 1
-- 2▶ Try it yourselfExample
-- products that are in stock but were never ordered
SELECT id FROM products WHERE stock > 0
EXCEPT
SELECT product_id FROM order_items;
-- Result:
-- id
-- --
-- 9▶ Try it yourselfOracle calls EXCEPT
MINUS. MySQL added INTERSECT and EXCEPT only in version 8.0.31.Key points
- LEFT JOIN ... WHERE right.id IS NULL finds missing matches.
- Self joins relate rows in the same table.
- UNION stacks results; UNION ALL keeps duplicates.
📝 Test yourself
1. What is the difference between UNION and UNION ALL?
2. Why write a.id < b.id in a self join?
3. Fill in the operator for rows in the first query but not the second:
SELECT ... SELECT ...
