IN Operator SQL

后端 未结 7 1514
庸人自扰
庸人自扰 2020-12-11 22:21

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,         


        
相关标签:
7条回答
  • 2020-12-11 23:03
     SELECT n FROM Nums  
     WHERE n IN (1, 2)
      Or n Is null
    

    This will retrieve what you intend to get. As said by Mitch normally a comparison to Null yields UNKNOWN. This is because NULL itself is defined as an undefined value. It's like saying I lived in Nottingham, Birmingham and somewhere. Finding somewhere on the world map can prove a bit tricky as it is undefined.

    0 讨论(0)
  • 2020-12-11 23:04

    If an IN list contains a NULL value anywhere, the result of the entire list is UNKNOWN

    With the correct default of ANSI NULLS, when you compare NULL with NULL the result is not true, but UNKNOWN

    0 讨论(0)
  • 2020-12-11 23:08

    You cannot compare directly with null. To find whether the value of a column is null, you must use something along the lines of this:

    SELECT n
    FROM Nums
    WHERE n IS NULL
    
    0 讨论(0)
  • 2020-12-11 23:13

    OK I have found the answer

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

    evaluates to

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

    The outcome of last comparison will always be UNKNOWN.
    and the truth table of AND shows that as soon as one Unknown is invloved in it (U,T)(U,F),(U,U) the reult can only be U or F (U=Unknown, F=False) and hence it will not be included in the result set.

    In case of

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

    equates to

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

    Now for the row with n=1, the operation n=1 will come as true
    and for the row with n=2, the operation n=2 will come as true
    and for all rows n=null will be unknown

    So it gives 1 and 2 in the result set.
    Hope u people liked it.
    CAN ANYONE PLEASE MARK MY REPLY AS ANSWER

    0 讨论(0)
  • 2020-12-11 23:13

    null is not returning, although included in IN operator

    Because of the n = NULL evaluation; NULL can't equal NULL. It would need to be handled as n IS NULL (or similar appropriate syntax) to return the NULL row/record.

    0 讨论(0)
  • 2020-12-11 23:14

    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

    0 讨论(0)
提交回复
热议问题