Self Joins and Hierarchies

SQL self join examples for managers, duplicates, comparisons, and basic hierarchy modeling.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Self joins
Employee to manager self join
SELECT e.employee_id,
       e.name AS employee_name,
       m.name AS manager_name
FROM employees e
LEFT JOIN employees m ON m.employee_id = e.manager_id;

# Resolve a manager relationship stored in the same table.

Find duplicate emails with self join
SELECT a.user_id, b.user_id, a.email
FROM users a
JOIN users b
  ON a.email = b.email
 AND a.user_id < b.user_id;

# Compare rows in the same table using inequality to avoid mirrored duplicates.

Pair records from the same day
SELECT a.id, b.id, a.event_date
FROM events a
JOIN events b
  ON a.event_date = b.event_date
 AND a.id < b.id;

# Generate pairs of rows that share a date.

## Hierarchy alternatives
Use self join for one-level hierarchy
One-level lookup: self join
Deep tree traversal: recursive CTE

# Great for direct parent relationships like employee → manager.

Recommended next

No recommendations yet.