Avatar of Starr Duskk
Starr Duskk
Flag for United States of America asked on

sql query returning unexpected results on NOT IN

I have  query that should return results, but doesn't.

First I have an employeeUnitJob table. It has no records in it for this employee:
The query is:
select * from EmployeeUnitJobType   where EmployeeId = 159795

Open in new window


It returns no rows as expected.

I want to do a query that returns the employees who have no rows in the employeeunitJobtype table, so I do this query, and just for testing I add the employeeID of this one employee that I know doesn't have a row in the table:

SELECT *
 FROM Employee 
   WHERE 
 Employee.EmployeeId NOT IN (select EmployeeId from EmployeeUnitJobType)
  AND EmployeeId = 159795

Open in new window


But this ALSO returns no rows. as though everyone has a unit/job and this person does not!

Is there something I am doing wrong? Why is the above query NOT returning any rows? it should return this employee?

thanks!
Microsoft SQL ServerMicrosoft SQL Server 2008Microsoft SQL Server 2005

Avatar of undefined
Last Comment
Starr Duskk

8/22/2022 - Mon
Scott Pletcher

Watching...
SOLUTION
dsacker

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Scott Pletcher

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Starr Duskk

ASKER
Both work, but I do prefer the second, although it might not be as politically correct. We have a lot of units and jobs per employee and I'm thinking the second might return multiple rows and I only want one row returned.

thanks!
Scott Pletcher

"NOT IN" is roughly equivalent to a "NOT EXISTS", both of which take advantage of the anti semi join.  SQL won't usually convert a left join and check for NULL into an anti join, and, if not, it's usually less efficient.

Btw, DISTINCT performs better than GROUPing when all you need to do is get distinct values, so if you do decide to use that approach, code it like this instead:
LEFT JOIN (SELECT DISTINCT EmployeeId from EmployeeUnitJobType) t
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Starr Duskk

ASKER
thanks scott!