Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem with NOT IN 3

Status
Not open for further replies.

bperry

Programmer
Jul 27, 2001
1,033
CA
Earlier in the week there was a discussion about NOT IN and NOT EXISTS. (I believe it was thread183-272715) That discussion reminded me of a problem with NOT IN that many people know about, but might be worth refreshing.

What do you think this will do?
[tt]
If 'Coconut' NOT IN ('Apple', 'Banana')
Print 'Return True: No, was not found in list'
Else
Print 'Return False: Yes, was found in list'
[/tt]

Of course, it returns:
Return True: No, was not found in list, because Coconut is not in the list.

What do you think this will do?
[tt]
If 'Coconut' NOT IN ('Apple', 'Banana', NULL)
Print 'Return True: Was not found in list'
Else
Print 'Return False: Was found in list'
[/tt]

Surprisingly, it returns:
Return False: Was found in list.

Apparently, the NULL in the IN values will cause the Select to return something different than what you expect. (At the root of this is the problem of comparing anything to NULL; you will always get 'not equal').

As I have presented it so far, this may seem like a trivial problem. But if you have something like this:

[tt]
Select * from tblProducts
Where ProductId NOT IN
(Select ProductId from tblSales)
[/tt]

then you might get unexpected results, and your query will not work properly, if the subquery returns any NULL values in its list.

I'm not sure if this is actually considered a 'bug' or not, but it certainly is unexpected behavior for most of us. One thing you could do to avoid this problem is to add some code to make sure the subquery returns no NULL values:

[tt]
Select * from tblProducts
Where ProductId NOT IN
(Select ProductId from tblSales
WHERE ProductId IS NOT NULL)
[/tt]

Perhaps even better would be to avoid NOT IN completely, by redesigning your query to use NOT EXISTS, or JOINS, instead of NOT IN.

-------------
bperry
 
Hi bperry,
This is a very helpful tip. You know I encountered this problem some time back, but then I could not find the cause. I was wondering why the heck this NOT IN is not working. Thanks a lot.
I solved the problem by writing a join statement. That way I could learn more about SQL. :)

Warm Regards
hmadhur
 
I think it isn't a bug because it works in the same way also in other DBMS
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top