Sub topic 1
Quick recap: how a join matches rows
Prerequisites
This chapter assumes you already know:
- Basic SELECT, WHERE, and ORDER BY
- INNER JOIN and LEFT JOIN with an ON condition
- Primary keys and foreign keys
- NULL handling in SQL
How a join matches rows
A join combines rows from two tables. The ON condition decides which pairs of rows match. For each row in the first table, the database checks the second table for rows where the ON condition is true, and it outputs one combined row for each match. An INNER JOIN drops rows with no match. A LEFT JOIN keeps every row from the left table and fills the right side with NULL when nothing matches.
A self join uses this same rule, with one table on both sides.
Why aliases matter when a table appears twice
When a table appears twice in one query, the database needs a way to tell the two copies apart. An alias is a short name for a table in the FROM clause. Each alias acts as a separate role for the same table. Without aliases, a column such as name is ambiguous, and the query fails.
SELECT e.name, m.name
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id;Here e plays the employee role and m plays the manager role. Each column names its alias, such as e.name or m.name.
Self joins: treating one table as two
A self join is a join where a table is joined to itself. You list the table twice with two aliases, then write an ON condition that links the copies. The database needs no special feature for this. It simply reads the table two times.
Employees and managers: reading a parent-child table
Some tables store a relationship inside themselves. The employees table below stores each employee's manager_id, which points to the id of another row in the same 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);Ava has no manager, so her manager_id is NULL. Ben and Chen both report to Ava. Dana reports to Ben.
> Using the self join from earlier, each row of e (the employee) finds the row of m (the manager) whose id equals e.manager_id.
Exercise
Using the employees table above, how many rows does the query "SELECT e.name, m.name FROM employees e INNER JOIN employees m ON e.manager_id = m.id;" return, and why?
Show answer
It returns 3 rows: Ben with Ava, Chen with Ava, and Dana with Ben. Ava has a NULL manager_id, so no row matches her in the ON condition, and the INNER JOIN drops her.