Sub topic 2
Keeping the top of the hierarchy with a LEFT self join
This chapter assumes you know SELECT, WHERE, and ORDER BY, INNER JOIN and LEFT JOIN with an ON condition, primary and foreign keys, NULL handling, and GROUP BY with SUM.
Keeping the top of the hierarchy with a LEFT self join
An INNER self join drops rows that have no matching parent. Ava has no manager, so an INNER join removes her. A LEFT JOIN keeps her and fills the manager column with NULL.
Create the sample table:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INT REFERENCES employees(id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ava', NULL),
(2, 'Ben', 1),
(3, 'Chen', 1),
(4, 'Dana', 2);Run the LEFT self join:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
ORDER BY e.id;All four employees appear. Ava's manager column is NULL.
Comparing rows: pairs without duplicates or mirror images
A self join on a shared value finds peers. Ben and Chen share manager 1. Without a filter, each pair appears twice (Ben with Chen, and Chen with Ben), and each row pairs with itself. The condition a.id < b.id keeps one ordering of each pair and removes self-pairs.
SELECT a.name AS first_employee, b.name AS second_employee
FROM employees a
INNER JOIN employees b
ON a.manager_id = b.manager_id
AND a.id < b.id;This returns one row: Ben and Chen.
Cross joins and the Cartesian product
A CROSS JOIN pairs every row of one table with every row of another. It has no ON condition. The row count equals the rows in the first table times the rows in the second. Three sizes and two colors produce 6 rows. This full pairing is called a Cartesian product.
CREATE TABLE sizes (size VARCHAR(2));
CREATE TABLE colors (color VARCHAR(10));
INSERT INTO sizes (size) VALUES ('S'), ('M'), ('L');
INSERT INTO colors (color) VALUES ('red'), ('blue');
SELECT s.size, c.color
FROM sizes s
CROSS JOIN colors c;CROSS JOIN versus the comma syntax
FROM sizes s, colors c returns the same result as the CROSS JOIN above. The comma form is easy to misuse. If a WHERE clause omits the join condition, the database silently returns a Cartesian product. Write CROSS JOIN when you want every combination, and check the row count of any join that should be selective.
Exercise:
Exercise
The employees table has 4 rows. How many rows does a CROSS JOIN of employees with itself return, and how would you remove the self-pairs and mirror pairs?
Show answer
It returns 16 rows (4 times 4). Add the condition a.id < b.id to an INNER JOIN on the same table, which keeps 6 unique pairs.