sqlcmd.net validated sql reference
advanced joining MySQL MariaDB SQL Server PostgreSQL SQLite

Join A Table To Itself With A Self-Join

Reference the same table twice using aliases to compare or relate rows within the same dataset.

Docker-validated Not currently validation-green

Find each employee and their manager from the same table

Alias e represents the employee row and alias m represents the manager row. LEFT JOIN is used so that Alice (the top-level manager with no manager of her own) still appears with a NULL manager rather than being excluded. Bob and Carol both report to Alice; Dave reports to Bob.

Rows loaded before the example query runs.
Setup
CREATE TABLE employees (id INT, name VARCHAR(50), manager_id INT);

INSERT INTO
  employees (id, name, manager_id)
VALUES
  (1, 'Alice', NULL),
  (2, 'Bob', 1),
  (3, 'Carol', 1),
  (4, 'Dave', 2);
Shared across supported engines.
SQL
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;
Returned rows for the shared example.
employeemanager
AliceNULL
BobAlice
CarolAlice
DaveBob

Output is identical across all engines.

Where this command helps.

  • relating rows within the same table
  • modeling manager, parent, or peer relationships without extra tables

What the command is doing.

A self-join treats one table as two separate sources by assigning different aliases. It is the standard pattern for hierarchical data — such as employees and their managers stored in the same table — where a foreign key points back to the same table's primary key.