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
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 .
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.
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.
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.
You want to put something like this:
select data,
case when data is null
then 'missing'
else 'not missing'
end as test from @t
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With