r/SQL • u/Medohh2120 • Mar 30 '26
Discussion I've been stuck on SQL self-joins for 6 months and I'm desperate, what is my mental model missing?
I've been struggling with SQL self-joins for about 6 months now and every tutorial I've found has failed me (including AI). They all just slam the query on the screen, run it, and the video ends. Nobody actually explains the mechanics. I already feel stupid enough so please be patient with me.
What I do understand:
- Self-joins are used for tree/hierarchical structures (like employee-manager)
- Reversing the ON condition in a normal join (two different tables) doesn't break anything because the table names keep the roles honest
- In a self-join, reversing the ON condition gives silently wrong results, the query runs fine, but the data is flipped
The classic table everyone uses:
| emp_id | name | manager_id |
|---|---|---|
| 1 | Alice | NULL |
| 2 | Bob | 1 |
| 3 | Carol | 1 |
| 4 | Dave | 2 |
Query A -- correct:
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.emp_idQuery B -- reversed, silently wrong:
sqlSELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON m.manager_id = e.emp_idWhat I've tried to understand:
I know that the ON clause is just a filter over all 16 possible row pairs (4×4). I can manually trace every pair and check which ones survive. That works I always get the right answer when I do it on paper. But I cannot keep drawing 16 rows by hand every time I write a query.
People keep telling me things like:
- "a manager has many employees but an employee has one manager" -- okay but how does that translate to which side of the = sign each column goes on?
- "think about the direction of the relationship" -- I stop and think, a manager IS also an employee in this table, so what does direction even mean?
- "the alias that holds the foreign key is the child" -- I understand foreign keys in normal joins but in a self-referencing table both aliases point to the same table so this still feels circular to me
I'm not looking for an analogy. I want the actual logic. What is everyone else seeing that I'm not?
