on ‎2013 Aug 07 4:38 PM
Why does the case expression ignore the condition I have to catch null values?
With this test table:
create table AATest (ID integer, Code varchar (5)); insert into AATest values (1, 'AAAA'); insert into AATest values (2, 'BBBB'); insert into AATest values (3, 'CCCC'); insert into AATest values (4, NULL); insert into AATest values (5, NULL);
and this select statement:
SELECT ID , case AATest.Code when 'AAAA' then 'A' when 'BBBB' then 'A' when 'CCCC' then 'A' when NULL then 'X' else 'U' end case as Status FROM AATest;
I would expect to get 3 rows of status 'A' and two rows of status 'X'. Instead I get 3 rows of status 'A' and two rows of status 'U'.
Why doesn't the When Null line match the null values?
This format does give my expected results:
SELECT ID , case when AATest.Code = 'AAAA' then 'A' when AATest.Code = 'BBBB' then 'A' when AATest.Code = 'CCCC' then 'A' when AATest.Code is NULL then 'X' else 'U' end case as Status FROM AATest;
SQL Anywhere version 12.0.1 build 3436
Request clarification before answering.
The first SELECT statement is an example of a 'simple case' statement where AATest.Code is being compared to NULL using the equality comparison (AATest.Code = NULL).
The second SELECT statement is an example of a 'searched case' statement where each condition is specified individually. This allows you to specify AATest.Code is NULL instead of AATest.Code = NULL
The expression AATest.Code = NULL will always evaluate to 'unknown' and never 'true', therefore the condition will never be satisfied. This is standard SQL behavior.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Got it. Thanks for the clarification. When handling this situation is it more common to use the searched case (which seems like quite a bit more typing) or use the simple case with a more filtered initial comparison like this:
SELECT ID , case coalesce(AATest.Code,'X') when 'AAAA' then 'A' when 'BBBB' then 'A' when 'CCCC' then 'A' when 'X' then 'X' else 'U' end case as Status FROM AATest;
Hm, besides the particular NULL comparison effect, I'd usually prefer the simple form if it's exactly "that simple case": i.e. comparing one expression to a set of constant values... - here, using the simple form is more comprehensible IMHO.
So I would not generally recommend the "searched case" - and unless one is aware of the "= NULL isn't IS NULL" problem, the searched case will tend to be a potential pitfall, as well...
NULLs are difficult, but usable:)
| User | Count |
|---|---|
| 9 | |
| 6 | |
| 4 | |
| 4 | |
| 3 | |
| 3 | |
| 3 | |
| 2 | |
| 2 | |
| 2 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.