Sub topic 4
Employees and Managers: Reading a Parent-Child Table
What you need to know
This chapter assumes that you can write basic SELECT queries, use INNER JOIN and LEFT JOIN with an ON condition, understand primary and foreign keys, and handle NULL values.
An employee-manager relationship is a parent-child relationship. Each employee is a child row. The employee's manager is the parent row. Both rows are stored in the same employees 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);The manager_id column is a foreign key. Its value points to the id of another row in the same table. Ava has no manager, so her manager_id is NULL.
Joining a table to itself
A self join is a join in which a table is used more than once in one query. SQL needs a different name for each use. A table alias is a temporary name given to a table in a query.
Here, e represents the employee row and m represents the manager row:
SELECT
e.name AS employee,
m.name AS manager
FROM employees AS e
INNER JOIN employees AS m
ON e.manager_id = m.id;The ON condition matches the employee's manager_id with the manager row's id.
| employee | manager |
|---|---|
| Ben | Ava |
| Chen | Ava |
| Dana | Ben |
The query does not return Ava. An INNER JOIN returns only rows with a match on both sides. Because Ava's manager_id is NULL, she has no matching manager row.
The aliases are necessary because the query refers to two roles from the same table. Without aliases, name and id would be ambiguous. Qualified names such as e.name and m.id show exactly which role supplies each column.
Keeping employees without managers
Use a LEFT JOIN when the report must include every employee, including the top of the hierarchy:
SELECT
e.name AS employee,
m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m
ON e.manager_id = m.id
ORDER BY e.id;This query returns:
| employee | manager |
|---|---|
| Ava | `NULL` |
| Ben | Ava |
| Chen | Ava |
| Dana | Ben |
The left side is the employee role. A LEFT JOIN keeps every row from that side. When no manager exists, columns from the manager alias contain NULL.
Common errors
- Reversing the join condition.
e.manager_id = m.idmeans “find the row referenced by this employee.” - Using an
INNER JOINwhen rows with no parent must remain. - Selecting an unqualified column such as
namewhen both aliases contain that column. - Filtering the manager in
WHEREwithout consideringNULL. For example,WHERE m.name = 'Ava'removes employees with no manager from the result. - Assuming this query finds every level below a manager. It finds one parent level only.
Exercise
Which join should you use to list every employee and show NULL for employees without a manager?
Show answer
Use a LEFT JOIN, with employees as the left-side table: LEFT JOIN employees AS m ON e.manager_id = m.id.