Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

sql server - IN Operator SQL

I have a table called NUMS with a single column n.
And I fill values 1,2,3,4,5,null in it.

Now a query

SELECT n FROM Nums 
 WHERE n IN (1, 2, null)

In this case I guess it's converted to

SELECT n FROM Nums 
 Where n = 1 OR n = 2 OR n = null   

I am also comparing n with a null value which should yield unknown and it should return an empty set.But it's returning 1,2 (null is not returning, although included in IN operator)

Now a query

SELECT n FROM Nums WHERE n NOT IN(1, 2, null)  

...gets converted to:

SELECT n FROM Nums 
 Where n!=1 AND n!=2 AND n!=null  

Here what I said above works and it does not return anything.

Can anyone explain in detail what's happening.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because null = null is always false the operator to use for null is IS or IS NOT You can use the query below for the expected output

SELECT n FROM Nums WHERE n IN (1,2) OR n IS NULL

[Edit]Thanx @Buckwad


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...