0Pricing
SQL Academy · Lesson

Self-Joins and Aliases

Join a table to itself using aliases to compare rows within the same table (employees and managers, dates and previous dates).

Self-Join: Joining a Table to Itself

Sometimes the relationship is within one table:

  • Employees ↔ Managers (manager is an employee)
  • Threaded comments (each comment has a parent_id)
  • Friend graph (user ↔ user)

The Setup

An employees table with a self-referencing FK:

CREATE TABLE employees (
  id BIGSERIAL PRIMARY KEY,
  full_name TEXT NOT NULL,
  manager_id BIGINT REFERENCES employees(id)
);

All lessons in this course

  1. Why Joins (Relational Model Recap)
  2. INNER JOIN Mechanics
  3. LEFT/RIGHT JOIN and OUTER Joins
  4. Self-Joins and Aliases
← Back to SQL Academy