简体   繁体   中英

Postgres NOT IN does not work as expected

I am trying to add the below condition in my query to filter data.

SELECT * 
FROM dump
WHERE letpos NOT IN ('0', '(!)','NA','N/A') ;

I need only records with id 1,2,3 and 6. But the query does not return ids 3 and 6. I get only 1,2.

TABLE:

id name letpos num
1 AAA A 60
2 BBB B
3 CCC 50
4 DDD 0
5 EEE (!) 70
6 FFF 70

I am not sure what is missing? Could anyone advise on how to resolve this?

-Thanks

In the row with id = 3 the value of letpos is (I suspect) NULL , so the boolean expression in the WHERE clause is:

WHERE NULL NOT IN ('0', '(!)','NA','N/A');

The comparison of NULL with operators like IN , NOT IN , = , > etc always returns NULL and is never TRUE .
So you don't get this row in the results.

Check for NULL also in the WHERE clause:

SELECT * 
FROM dump 
WHERE letpos IS NULL
   OR letpos NOT IN ('0', '(!)', 'NA', 'N/A');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM