Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case when null not working as expected

consider this very short T-SQL code that does a test on a nullable column using a case

declare @t table(data varchar(10) null)
insert into @t values('something')
insert into @t values(null)

select data, 
    case data when null
        then 'missing'
        else 'not missing'
    end as test
from @t

the output that I get is:

data        test
---------   -----------
something   not missing
NULL        not missing

However what I was expecting was

data        test
---------   -----------
something   not missing
NULL        missing

What am I missing concerning the test on this nullable value

like image 527
Ralph Shillington Avatar asked Aug 03 '11 15:08

Ralph Shillington


People also ask

How do you handle NULL values in a case statement?

SQL offers two case abbreviations to cope with null : coalesce and nullif . Both are used like functions and do not use the keywords case , when , then , else and end .

IS NOT NULL condition in case statement SQL Server?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

What are the problems with NULL values?

The NULL value can cause problems when selecting data. However, because when comparing an unknown value to any other value, the result is always unknown and not included in the results. You must use the IS NULL or IS NOT NULL operators to check for a NULL value.

Is NULL in case in SQL?

The SQL CASE Expression If no conditions are true, it returns the value in the ELSE clause. If there is no ELSE part and no conditions are true, it returns NULL.


2 Answers

You want to put something like this:


select data,      
case when data is null         
then 'missing'         
else 'not missing'     
end as test from @t 

like image 62
M.R. Avatar answered Oct 13 '22 00:10

M.R.


case might not work with null. Use coalesce or isnull.

declare @t table(data varchar(10) null)
insert into @t values('something')
insert into @t values(null)

select data, 
case coalesce(data, 'missing')
    when 'missing' then 'missing'
    else 'not missing'
end as test
from @t
like image 36
ek_ny Avatar answered Oct 13 '22 01:10

ek_ny