Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
538 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers 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
Search our website
We also send out useful tips in a monthly email newsletter ...
Did you know there was an IIF function in SQL to test conditions? We didn't! |
---|
You can use the IIF function in SQL as an alternative to the CASE WHEN statement. We thought we would share this new (for us) discovery with the world! |
In this blog
So how long have we been teaching SQL for now (at introductory and advanced level)? Ten years? More? And yet none of us (apart from Sam) knew that you could use the IIF function when writing SQL.
Thanks to Adrian Dilworth for asking the relevant question on a recent SQL course. What would we do without our course delegates?
So supposing you want to report on whether films won Oscars or not. Here's how you could do this if you were so lamentably ignorant as not to know about the IIF function:
SELECT
f.Title,
f.OscarWins,
f.OscarNominations,
-- was this person a winner
CASE
WHEN f.OscarWins > 0 THEN 'Winner'
ELSE 'Loser'
END AS OscarStatus
FROM
Film AS f
And here are the first few rows that this might show:
The first few films, with their all-important Oscar status.
You could more easily write the same query using the IIF function:
SELECT
f.Title,
f.OscarWins,
f.OscarNominations,
-- was this person a winner (using IIF)
IIF(
f.OscarWins > 0,
'Winner',
'Loser'
) AS OscarStatus
FROM
Film AS f
The syntax of this function is identical to that of the IF function in Excel. The 3 arguments are: 1) the condition to test, 2) what to do if it's true and 3) what to do if it's false.
As in Excel, you can nest IIF functions within each other to test multiple, mutually exclusive possibilities. For example, the following query would show for each film whether it was an Oscar winner, nominee or loser:
SELECT
f.Title,
f.OscarWins,
f.OscarNominations,
-- was this person a winner, nominee or loser
IIF(f.OscarWins > 0,'Winner',
IIF(f.OscarNominations > 0, 'Nominee','Loser')
) AS OscarStatus
FROM
Film AS f
Once you're testing more than two conditions, you're probably better off writing a CASE WHEN statement instead (or in Excel 2016 or later, the SWITCH function).
Some other pages relevant to the above blog include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2024. All Rights Reserved.