Skip to content
Advertisement

Finding an ID not in another column

I’m working on a little SQL exercise, and am scratching my head an this problem.

I am trying to find all the Employees to whom no other employee reports to. This is what the employees table looks like:

I thought a straightforward one of these queries would do it:

But those return the following results, which isn’t what I’m looking for:

Why is NOT IN returning items that are definitely in that column? How would I go about returning items not in ReportsTo if I am using NOT IN incorrectly?

Advertisement

Answer

The problem with your 1st query is that you use NOT IN with a list that contains a NULL value.
So a comparison of an EmployeeId like say 5:

will return NULL, because any comparison to NULL returns NULL and that EmployeeId will not be included in the results.
Change to:

See the demo.
Results:

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