2

The NOT IN clause is omitting the NULL values when checking the condition.

INPUT  
ID  NAME  
1   A  
2   <null>
3   C

SELECT... FROM...
WHERE NAME NOT IN ('C')

is only returning ID value 1. I need both 1 & 2.

Could this be done?

athresh
  • 553
  • 6
  • 11
  • 24

4 Answers4

5
WHERE NAME NOT IN ('C') OR NAME IS NULL
zerkms
  • 249,484
  • 69
  • 436
  • 539
3

Either you check NULL values

select *
from not_in
where name not in ('C') or name is null;

or you can convert NULL values in any other character with coalesce. I use ' ' in the sample below.

select *
from not_in
where coalesce(name, ' ') not in ('C');
Olaf H
  • 496
  • 2
  • 9
2

Correct SQL would be

SELECT... FROM...
WHERE NAME NOT IN ('C')
or NAME is NULL

That's because any comparisons with NULL also yield NULL (i.e. not truthy nor falsy). (Credit to @Jack)

Refer:
MySQL: Why is NULL ignored in MySQL?
Working of Null Values

Community
  • 1
  • 1
asifsid88
  • 4,631
  • 20
  • 30
0
SELECT... 
FROM...
WHERE NAME NOT IN ('C') 
    OR NAME IS NULL

SELECT... 
FROM...
WHERE ISNULL(NAME, '') NOT IN ('C') 
gareththegeek
  • 2,362
  • 22
  • 34
  • 1
    `ISNULL(NAME, '') NOT IN ('C') ` will never be optimized. Should be never assumed as a solution. – zerkms Jul 09 '13 at 09:25
  • agreed - using any function on a column invalidates the index; this is why I cringe when I see code like "WHERE lower(username) = :param" then I'm asked why this query is so slow "there's an index on username!" – Trent Jul 09 '13 at 09:28
  • @zerkms - although `NAME NOT IN ('C') OR NAME IS NULL` will probably result in a full table scan, at least on Oracle. – APC Jul 09 '13 at 09:58
  • @APC: `NOT IN` would for any B-Tree based indexes. For oracle - depending on the index type. If you have bitmap there is a chance it won't. – zerkms Jul 09 '13 at 10:23