Using the CASE statement
This is most easily accomplished in all versions of SQL Server using theCASEstatement, which acts as a logicalIF...THEN...ELSE
expression and returns various values depending on the result.
In this example below, we want to return an additionallocale
column that specifies whether our book takes place in Middle-earth or regular old Earth.
SELECT
CASE
WHEN
books.title='TheHobbit'
THEN
'Middle-earth'
WHEN
books.primary_author='Tolkien'
THEN
'Middle-earth'
ELSE
'Earth'
ENDASlocale,
books.*
FROM
books
Before we examine the specialCASE
aspect of this statement, let’s temporarily remove theCASE
to notice that this is an extremely simpleSELECT
statement on the surface:
SELECT
books.*
FROM
books
Therefore, let’s examine how theCASE
section is structured and what logical behavior we’re performing.
CASE
WHEN
books.title='TheHobbit'
THEN
'Middle-earth'
WHEN
books.primary_author='Tolkien'
THEN
'Middle-earth'
ELSE
'Earth'
ENDASlocale
To begin, we of initialize theCASE
statement then specify under which conditions (WHEN
) ourCASE
statement should evaluate a result. In this example, we’re examining thebooks.title
andbooks.primary_author
; if either fit our Tolkien-esque theme,THEN
we return the value ‘Middle-earth.’ If neither fields match our search, we instead return the value of ‘Earth.’
To rearrange the logic as a psuedo-codeIF...THEN...ELSE
statement, we’re simply asking SQL to evaluate:
IF
title=='TheHobbit'OR
primary_author=='Tolkien'
THEN
RETURN'Middle-earth'
ELSE
RETURN'Earth'
END
Finally, it is critical to remember that aCASE
statement must always be appended at the end with a matchingEND
statement. In the above example, we’re also renaming the resulting value that is returned tolocale
, though that is certainly optional.
Using the IIF function
If you are using a more modern version of SQL, it is useful to know that SQL Server 2012 introduced the very handyIIFfunction.IIF
is a shorthand method for performing anIF...ELSE/CASE
statement and returning one of two values, depending on the evaluation of the result.
Restructuring our above example to useIIF
is quite simple.
SELECT
IIF(
books.title='TheHobbit'ORbooks.primary_author='Tolkien',
'Middle-earth',
'Earth')
ASlocale,
books.*
FROM
books
With anIIF
function, we largely replace a lot of the syntactical sugar from theCASE
statement with a few simple comma-seperators to differentiate our arguments.
All told, bothCASE
andIIF
get the same job done, but if given the choice,IIF
will generally be much simpler to use.