I was debugging a procedure in an oracle database when I came across something that surprised me regarding NULL values. Can anybody explain why the following query returns false for the non equality check here?
DECLARE
vNullVariable VARCHAR2(2) := NULL;
vVariable VARCHAR2(2) := 'Hi';
BEGIN
IF vNullVariable <> vVariable THEN
dbms_output.put_line( 'The variables are not equal' );
ELSE
dbms_output.put_line( 'The variables are equal' );
END IF;
END;
This is because SQL uses three-valued logic (3VL): there is TRUE, there is FALSE and there is NULL (unknown, neither TRUE nor FALSE).
The result of the expression
vNullVariable <> vVariableis NULL, not TRUE, in 3VL because it considers the value of vNullVariable to be unknown: if at a later time it becomes a known value, it might be ‘Hi’ or it might not, but right now SQL doesn’t know so it returns NULL (unknown).So the IF expression evaluates to NULL, not TRUE, and so the default ELSE path is taken instead – because the logic if IF is:
This means that you would get the behaviour you were expecting if you wrote the check the other way around: