559 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
How to do calculations and expressions in T-SQL
Part five of a five-part series of blogs
You can use SQL to do everything from simple arithmetic through to complicated functions - this blog gives you the low-down!
The final part of this blog looks at the thorny issue of nulls. You can get one of these in a table by pressing CTRL + 0, although usually they're already there!
In this table of people, we've removed one person's first name.
There are 3 possible ways to deal with nulls in expressions: using IsNull, Coalesce or CASE. I've explained these under separate headings below!
This function substitutes a given value when a column is null. The syntax is:
Here's an example, showing someone's first name for the table above:
-- show people's names
IsNull(FirstName, 'Not given') AS 'First name',
Here's what this would give for our table above:
SQL has substituted the words Not given when the first name is null.
This strangely-named function allows you to try multiple values. The syntax is:
Here's an example, returning someone's phone number by trying various columns in turn:
-- get valid phone number
'No phone number given'
) AS Phone
You can always use COALESCE instead of ISNULL, by just including two arguments for it.
This is my personal favourite, since it builds on something with which every SQL programmer should be familiar - the CASE statement (see previous part of this blog). We could show the first name for the example at the start of this page as follows:
-- show first name without null
WHEN FirstName is null THEN 'Not given'
END AS 'First name',
This would give the same results:
The second column gives the first names of people, but with null values removed.
And that is the end of my blog on calculations in SQL!
|Parts of this blog|
25 Aytoun Street