Testing for NULL
— if it matters
Quite often, you don’t need to take special measures for fields or variables that may be NULL
.For instance, if you do this:
select * from Customers where Town = 'Ralston'
you probably don’t want to see the customers whose town is unspecified.Likewise:
if (Age >= 18) then CanVote = 'Yes'
doesn’t include people of unknown age, which is also defensible.But:
if (Age >= 18) then CanVote = 'Yes';
else CanVote = 'No';
seems less justified: if you don’t know a person’s age, you shouldn’t explicitly deny her the right to vote.Worse, this:
if (Age < 18) then CanVote = 'No';
else CanVote = 'Yes';
won’t have the same effect as the previous.If some of the NULL
ages are in reality under 18, you’re now letting minors vote!
The right approach here is to test for NULL
explicitly:
if (Age is null) then CanVote = 'Unsure';
else if (Age >= 18 ) then CanVote = 'Yes';
else CanVote = 'No';
Since this code handles more than two possibilities, using the CASE
syntax (supported by Firebird 1.5 and up) is more elegant:
CanVote = case
when Age is null then 'Unsure'
when Age >= 18 then 'Yes'
else 'No'
end;
Or, prettier:
CanVote = case
when Age >= 18 then 'Yes'
when Age < 18 then 'No'
else 'Unsure'
end;