Not in not return null value

Lylyy 380 Reputation points
2023-10-26T02:31:45.28+00:00

I have this query

Declare @tbl table (id int,val varchar(10)); 
insert into @tbl values (1,null), (2,'aaa'), (3,'bbb'), (4,null), (5,'ccc')

select * from @tbl 
where val not in ('aaa','bbb') 

The result is only 5 ccc. Why id 1 and 4 are not in the result?

Developer technologies Transact-SQL
SQL Server Other
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,566 Reputation points
    2023-10-26T02:39:42.3433333+00:00

    Hi @Lylyy

    Syntax: test_expression [ NOT ] IN ( subquery | expression [ ,...n ] )

    Any null values returned by subquery or expression that are compared to test_expression using IN or NOT IN return UNKNOWN.

    Please refer to this doc for more details: IN (Transact-SQL).

    To return null value, you may try this query:

    select * from @tbl
    where isnull(val,'') not in ('aaa','bbb') 
    

    Best regards,

    Cosmog Hong

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2023-10-26T02:40:01.9+00:00

    select * from @tbl

    where val not in ('aaa','bbb') or val is null

    select * from @tbl a

    where not exists (select 1 from @tbl where a.val in ('aaa','bbb') )

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.