0PricingLogin
SQL Academy · Lesson

Comparing Rows in the Same Table

Find pairs and relationships.

What Is a Self Join?

A self join is when you join a table to itself. This sounds unusual at first, but it is a powerful technique for comparing rows within the same table.

Imagine an employees table where each employee has a manager_id that points to another row in the same table. A self join lets you match each employee with their manager in a single query.

Setting Up the Example Table

Let us create a simple employees table to use throughout this lesson. Each row has an id, a name, a salary, and a manager_id that references another employee in the same table.

CREATE TABLE employees (
  id         INT PRIMARY KEY,
  name       VARCHAR(50),
  salary     INT,
  manager_id INT
);

INSERT INTO employees VALUES
  (1, 'Alice',   90000, NULL),
  (2, 'Bob',     70000, 1),
  (3, 'Carol',   65000, 1),
  (4, 'Dave',    55000, 2),
  (5, 'Eve',     60000, 2),
  (6, 'Frank',   48000, 3);

All lessons in this course

  1. What Is a Self Join
  2. Employees and Managers
  3. Comparing Rows in the Same Table
  4. Limits of Self Joins
← Back to SQL Academy