Self Join & UNION
Join a table to itself to find hierarchical relationships, and combine result sets from multiple queries into one.
Self Join compares rows within the same table. UNION stacks two query results on top of each other.
EXERCISE
1Self Join — A Table Joining Itself
A Self Join joins a table to itself. This sounds strange but is the natural solution for hierarchical data — like employees and their managers in the same table.
The classic use case — employee-manager hierarchy:
-- employees table:
-- id | name | manager_id
-- 1 | Ravi | NULL ← CEO, no manager
-- 2 | Priya | 1 ← reports to Ravi
-- 3 | Arjun | 1 ← reports to Ravi
-- 4 | Sunita | 2 ← reports to Priya
-- 5 | Kiran | 2 ← reports to Priya
-- Self Join to get employee + manager name:
SELECT
e.name AS employee,
m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
-- Output:
-- employee | manager
-- Ravi | NULL ← no manager
-- Priya | Ravi
-- Arjun | Ravi
-- Sunita | Priya
-- Kiran | Priya
Why LEFT JOIN instead of INNER JOIN here:
Using INNER JOIN would exclude Ravi (the CEO) since manager_id = NULL has no match. LEFT JOIN keeps all employees including those with no manager.
Finding employees who earn more than their manager:
SELECT
e.name AS employee,
e.salary AS emp_salary,
m.name AS manager,
m.salary AS mgr_salary
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id
WHERE e.salary > m.salary;
Pro Tip: Self Join always requires aliases — one alias for the "employee role" and one for the "manager role". Without aliases, MySQL cannot tell which copy of the table you mean.
EXERCISE
2UNION & UNION ALL — Combining Query Results
UNION stacks the results of two or more SELECT queries on top of each other. Both queries must return the same number of columns with compatible types.
UNION — stack two result sets:
-- All customers and all suppliers in one list:
SELECT name, email, 'customer' AS type
FROM customers
UNION
SELECT name, email, 'supplier' AS type
FROM suppliers
ORDER BY name;
UNION vs UNION ALL:
-- UNION: removes duplicates (slower — must compare every row):
SELECT email FROM customers
UNION
SELECT email FROM subscribers;
-- UNION ALL: keeps all rows including duplicates (faster):
SELECT email FROM customers
UNION ALL
SELECT email FROM subscribers;
-- Use UNION ALL when you know there are no duplicates, or duplicates are OK
Rules for UNION:
-- 1. Same number of columns in each query
-- 2. Compatible data types in matching columns
-- 3. Column names come from the FIRST query
-- 4. ORDER BY and LIMIT apply to the final combined result (put at end)
SELECT name, price FROM products WHERE category = 'Electronics'
UNION ALL
SELECT name, price FROM products WHERE category = 'Mobiles'
ORDER BY price DESC
LIMIT 10;
Finding data in one table but not the other:
-- Emails in subscribers but NOT in customers:
SELECT email FROM subscribers
WHERE email NOT IN (SELECT email FROM customers);
-- Alternative using UNION logic pattern:
SELECT email FROM subscribers
LEFT JOIN customers USING (email)
WHERE customers.email IS NULL;
Pro Tip: UNION deduplicates by comparing every column of every row — this is expensive on large datasets. Use UNION ALL whenever possible and filter duplicates differently if needed.
EXERCISE
3CROSS JOIN & When to Use It
CROSS JOIN produces every possible combination of rows from two tables. It has niche but legitimate use cases — and is accidentally triggered more often than you think.
What CROSS JOIN does:
-- If table A has 3 rows and table B has 4 rows:
-- CROSS JOIN produces 3 × 4 = 12 rows (every combination)
SELECT
colours.name AS colour,
sizes.name AS size
FROM colours
CROSS JOIN sizes;
-- Output (3 colours × 3 sizes = 9 combinations):
-- colour | size
-- Red | S
-- Red | M
-- Red | L
-- Blue | S
-- Blue | M
-- Blue | L
-- Green | S
-- Green | M
-- Green | L
Legitimate uses of CROSS JOIN:
-- 1. Generate all possible product variants (colour × size × material):
FROM colours CROSS JOIN sizes CROSS JOIN materials
-- 2. Build a date scaffold (every date × every category for reporting):
FROM calendar_dates CROSS JOIN product_categories
-- 3. Pair every employee with every project to create an assignment grid
FROM employees CROSS JOIN projects
Accidental CROSS JOIN — a very common bug:
-- Missing the ON condition creates an accidental CROSS JOIN:
SELECT * FROM orders, customers; -- old syntax, CROSS JOIN!
SELECT * FROM orders JOIN customers; -- also CROSS JOIN (no ON)
-- If orders has 10,000 rows and customers has 5,000:
-- Result: 50,000,000 rows (can crash a database)
Pro Tip: The old-style
FROM table1, table2 WHERE ...syntax is a CROSS JOIN with a WHERE filter — which is functionally the same as INNER JOIN but much harder to read. Always use explicit JOIN ... ON syntax.
