SQL: a self join relates a table to itself

Two aliases on the same table let you compare rows to other rows - an employee to a manager, a reading to the previous reading. The aliases are what make the columns unambiguous.

Code
SELECT e.name AS employee, m.name AS manager
  FROM employee e
  LEFT JOIN employee m ON m.id = e.manager_id;

-- A window function is often clearer for row-to-row comparison:
SELECT reading_at, value,
       value - LAG(value) OVER (ORDER BY reading_at) AS delta
  FROM meter;
Output
employee | manager
Ann      | NULL
Bob      | Ann

reading_at | value | delta
09:00      |  100  | NULL
09:05      |  118  |   18

-- LEFT is important in the first query: an INNER JOIN would silently drop
-- anyone without a manager, usually the CEO.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25