r/SQL • • Oct 13 '25

Discussion Still Confused by SQL Self-Join for Employee/Manager — How Do I “Read” the Join Direction Correctly?

I am still learning SQL, This problem has been with me for months:

SELECT e.employee_name, m.employee_name AS manager_name

FROM employees e

IINER JOIN employees m ON e.manager_id = m.employee_id;

I can't get my head around why reversing aliases yields different results since they are the same table like:

SELECT e.employee_name, m.employee_name AS manager_name

FROM employees e

IINER JOIN employees m ON m.manager_id = e.employee_id;

Could someone please explain it to me in baby steps?

edit: thanks for help everyone, I now get it if I draw it manually and use Left join matching algorithm, got both from commenters thanks!!, when I read how the rest thought my mind couldn't take it but I will be back!

20 Upvotes

28 comments sorted by

View all comments

Show parent comment

1

u/squadette23 Oct 15 '25

> corect me if i am wrong but yea as mentioned above: "generalized left join" is triggered only when there'sn't id joining

yes.

> what the guy in the link

I am the guy in the link btw.

Your example with statuses is great, but I think that I disagree that

> LEFT JOIN b ON a.id = b.a_id AND b.status = 'Active';

> this returns expected results

I mean, of course yes, this is exactly how LEFT JOIN actually works, so you can say that this is "expected result". BUT: I believe that there are some scenarios where this is actually not what you expect (because you did not look closely enough or you're tired).

If I glance at the query and I see "b.status = 'Active'" I would probably expect to only see active results! (And note that with INNER JOIN this is exactly how it works!)

Also, here it's clearly visible because we have small clear queries and we can discuss them. But what if this is a subquery in some huge query of hundreds of lines. You may not be so lucky to notice that one of them has this gotcha.

Back in the day I wrote this example of generalized LEFT JOIN gotcha: https://docs.google.com/document/d/1d22QtBRFthalVn3Y8UhtYQ4IDf3qkmcLHNL23JE-r7s/edit?usp=sharing (as google docs because it contains some tables for reference). Commenting is enabled.

I'm also going to write another example, somewhat based on your example.