Skip to content
Advertisement

Simple PostgreSQL Self Join

This is what my employee table looks like where manager_id is Foreign Key to the same table it references to employee_id and indicates which employee has manager and who is.

I did self left join and the result was what was expected.

But this query gives me

So I don’t understand why it returns something instead of nothing.employee_id will never be a NULL…

http://sqlfiddle.com/#!17/6e6af/9

Advertisement

Answer

employee_id will never be a NULL…

The null value comes from column e.manager_id (not column m.employee_id ) – that’s Windy Hays, the top employee in hierarchical tree.

For this particular row, the left join that attempts to retrieve the corresponding manager does not find a match – so now m.employee_id is null in the resultset.

Maybe the where clause you wanted to write is:

… Which indeed will return no rows, as one would expect.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement