Video in progress

What is a self join? Show it with an employee and their manager.

A self join joins a table to itself. You need it when a row in a table refers to another row of the same table, for example an employee's manager_id column also points to another employee in the employees table.

📖 Answer

CREATE TABLE employees (
    id         bigint PRIMARY KEY,
    name       text NOT NULL,
    manager_id bigint REFERENCES employees(id)
);

SELECT e.name AS xodim, m.name AS rahbar
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;

Because the same table gets two different aliases (e and m), SQL treats them as two separate tables. The LEFT JOIN matters: the CEO has no manager (manager_id IS NULL), and a plain JOIN would drop them from the list.

Other examples: a category tree (parent_id), "pairs of users in the same city", comparing consecutive events.

If you need a multi-level hierarchy (the manager's manager and so on), chaining self joins gets awkward, and WITH RECURSIVE is made for that.