Employees and Managers
A classic hierarchy example.
What Is a Self Join?
A self join is when a table is joined to itself. This sounds unusual, but it is extremely useful when rows in a table have a relationship with other rows in the same table.
The classic example is an employees table where each employee may have a manager — and that manager is also an employee stored in the same table.
The Employees Table
Let us create a simple employees table. Each employee has an id, a name, and a manager_id that points back to another row in the same table.
When manager_id is NULL, the employee has no manager — they are at the top of the hierarchy (e.g., the CEO).
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
manager_id INT REFERENCES employees(id)
);All lessons in this course
- What Is a Self Join
- Employees and Managers
- Comparing Rows in the Same Table
- Limits of Self Joins