1

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
6
  • 5
    This is the expected behavior. That is how NULL values work -- all comparisons other than is null return the equivalent of false. Commented Mar 8, 2016 at 12:36
  • 1
    stackoverflow.com/questions/12853944/… Commented Mar 8, 2016 at 12:42
  • I tested it was working with "is null" but didnt know the reason. thanks. Commented Mar 8, 2016 at 12:45
  • @FlorinGhita I searched it for long time but couldn't find the right google query to match the question. Thanks for the link. Commented Mar 8, 2016 at 12:48
  • I've search on stackoverflow "SQL NULL" :) Commented Mar 8, 2016 at 12:52

1 Answer 1

2

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 NULLs then you can do:

select count(*) from table where statuscode <> 13 OR statuscode IS NULL
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.