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?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,817 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,639 questions
{count} votes

Accepted answer
  1. LiHongMSFT-4306 27,016 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,891 Reputation points
    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.