SQL practice

SQL self join practice questions

8 problems, ordered from easiest. They run in your browser, and 1 is free.

Start with Employees earning more than their manager

The idea in a minute

A self join joins a table to itself. You give the table two aliases and treat them as two copies, for example one copy for the employee and one for the manager.

Use it when a row points at another row in the same table, or when you want to compare rows with each other.

Example: Employee and manager names

CREATE TABLE staff AS SELECT * FROM (VALUES (1,'Priya',NULL),(2,'Karan',1),(3,'Isha',1),(4,'Dev',2)) t(id, name, manager_id);
SELECT e.name AS employee, m.name AS manager
FROM staff e
LEFT JOIN staff m ON e.manager_id = m.id
ORDER BY e.id

What it prints

employee  manager
Priya     NULL
Karan     Priya
Isha      Priya
Dev       Karan

What to watch for

  • Always give the two copies different aliases, or SQL cannot tell the columns apart.
  • Use a LEFT JOIN if people without a match, such as the top manager, must still appear.
  • To compare pairs, use a condition like a.id < b.id so each pair appears once.

Self Joins problems

  1. Employees earning more than their managerbeginner · Free
  2. Employee and manager namesintermediate · Locked
  3. Products most often bought togetherintermediate · Locked
  4. Near-salary pairs in a departmentadvanced · Locked
  5. Overlapping meetings in a roomadvanced · Locked
  6. Slow request-to-accept tripsadvanced · Locked
  7. Pages liked by people you followadvanced · Locked
  8. Strong mutual friendsadvanced · Locked

Want a guided order across every topic? Open the practice sheets or the SQL hub.