Is there better Oracle operator to do null-safe equality check?

前端 未结 3 1748
醉梦人生
醉梦人生 2020-12-19 23:34

According to this question, the way to perform an equality check in Oracle, and I want null to be considered equal null is something like

SELECT  COUNT(1)
           


        
3条回答
  •  时光说笑
    2020-12-20 00:28

    As an alternative you can use NVL function and designated literal which will be returned if a value is null:

    -- both are not nulls
    SQL> with t1(col1, col2) as(
      2    select 123, 123 from dual
      3  )
      4  select 1 res
      5    from t1
      6  where nvl(col1, -1) = nvl(col2, -1)
      7  ;
    
           RES
    ----------
             1
    
    -- one of the values is null
    SQL> with t1(col1, col2) as(
      2    select null, 123 from dual
      3  )
      4  select 1 res
      5    from t1
      6  where nvl(col1, -1) = nvl(col2, -1)
      7  ;
    
      no rows selected
    
     -- both values are nulls
     SQL> with t1(col1, col2) as(
      2    select null, null from dual
      3  )
      4  select 1 res
      5    from t1
      6  where nvl(col1, -1) = nvl(col2, -1)
      7  ;
    
           RES
    ----------
             1
    

    As @Codo has noted in the comment, of course, above approach requires choosing a literal comparing columns will never have. If comparing columns are of number datatype(for example) and are able to accept any value, then choosing -1 of course won't be an option. To eliminate that restriction we can use decode function(for numeric or character datatypes) for that:

     with t1(col1, col2) as(
      2    select null, null from dual
      3  )
      4  select 1 res
      5    from t1
      6  where decode(col1, col2, 'same', 'different') = 'same'
      7  ;
    
           RES
    ----------
             1
    

提交回复
热议问题