简体   繁体   中英

oracle sql filter for nullable values

Is that expected behavior for oracle 11g. Can someone explain why last query does not include null value?

table

statuscode
13
null
---------------------------------------------------------
select count(*) from table -- returns 2
select count(*) from table where statuscode = 13 --returns 1
select count(*) from table where statuscode <> 13 --returns 0

Think of NULL as an unknown value and testing if something equals (or does not equal) an unknown will result in an unknown ( NULL ) as the answer. The SQL query will display results when the boolean filter is TRUE and this will not be the case if one value is NULL .

You can test the logic in PL/SQL (since it has an accessible BOOLEAN type):

SET SERVEROUTPUT ON;
DECLARE
  FUNCTION bool_to_string( bool BOOLEAN ) RETURN VARCHAR2
  AS
  BEGIN
    RETURN CASE WHEN bool IS NULL  THEN 'NULL'
                WHEN bool =  TRUE  THEN 'TRUE'
                WHEN bool =  FALSE THEN 'FALSE'
                ELSE                    'ERROR' END;
  END;
BEGIN
  DBMS_OUTPUT.PUT_LINE( 'A =  A    => ' || bool_to_string( 'A' = 'A' ) );
  DBMS_OUTPUT.PUT_LINE( 'A <> A    => ' || bool_to_string( 'A' <> 'A' ) );
  DBMS_OUTPUT.PUT_LINE( 'A =  NULL => ' || bool_to_string( 'A' = NULL ) );
  DBMS_OUTPUT.PUT_LINE( 'A <> NULL => ' || bool_to_string( 'A' <> NULL ) );
END;
/

Which outputs:

A =  A    => TRUE
A <> A    => FALSE
A =  NULL => NULL
A <> NULL => NULL

Note that the last two tests do not return FALSE but return NULL .

If you want to count including NULL s then you can do:

select count(*) from table where statuscode <> 13 OR statuscode IS NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM