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
545 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 ...
Written by Andy Brown
In this tutorial
All you programmers out there who have been following this tutorial are probably salivating now at the prospect of getting stuck into some proper programming. Salivate not, because ...
IF conditions are not that commonly used in SQL; if you find yourself littering your SQL with conditions, you're probably doing something wrong. You could do worse than to book a place on one of our introductory or advanced SQL courses, which we now offer online also.
Notwithstanding the hint above, there is a place for IF statements in SQL. Let's first have a look at the syntax, then consider some examples.
The way you write an IF statement in SQL is as follows:
-- test if a condition is true
IF (condition true)
DO SOMETHING
To make it clearer what's going on (and to allow you to run a number of different statements if a condition is true), use BEGIN and END as bookmarks:
-- test if a condition is true
IF (condition is true)
BEGIN
DO ONE THING
DO ANOTHER THING
END
My advice would be always to use BEGIN / END, especially if you come from a VB background. Oh, and resist that temptation to put the word THEN after the condition!
Suppose you want to say: if one thing is true, do this; otherwise, do that. For this, you'll need to use the ELSE keyword. The syntax is:
-- test if a condition is true
IF (condition is true)
BEGIN
DO THING A
DO THING B
END
ELSE
BEGIN
DO THING C
DO THING D
DO THING E
END
If you want to test more than two conditions, you're going to have to nest your IF statements. For example:
-- test if any one of 3 conditions is true
IF (condition is true)
BEGIN
DO THING A
END
ELSE
IF (condition 2 is true)
BEGIN
DO THING B
END
ELSE
BEGIN
DO THING C
END
It's probably worth adding that in all my SQL programming career I've never built this complex an IF statement; you should be using CASE statements instead!
The following is valid SQL: it will print a suitable message according to the day of the week:
Day of week | Number | Message |
---|---|---|
Saturday, Sunday | 7, 1 | It's the weekend! |
Friday | 6 | It's Friday ... |
Any other day | 2 to 5 | It's a weekday ... / Time to work ... |
Here's the SQL without indentation - it's nigh on impossible to read:
-- print different messages according to
-- the day of the week
IF DatePart(weekday,GetDate()) IN (1,7)
PRINT 'It''s the weekend!'
ELSE
IF DatePart(weekday,GetDate()) = 6
PRINT 'It''s Friday ...'
ELSE
BEGIN
PRINT 'It''s a weekday ...'
PRINT 'Time to work ...'
END
If we add proper indentation, everything suddenly becomes much clearer:
-- print different messages according to
-- the day of the week
IF DatePart(weekday,GetDate()) IN (1,7)
PRINT 'It''s the weekend!'
ELSE
IF DatePart(weekday,GetDate()) = 6
PRINT 'It''s Friday ...'
ELSE
BEGIN
PRINT 'It''s a weekday ...'
PRINT 'Time to work ...'
END
OK - having looked at the syntax of the IF statement, let's look at some examples.
The following query prints out a suitable message if SQL Server can find films which won ten or more Oscars:
-- see if there are any films winning
-- ten or more Oscars
IF EXISTS (
SELECT * FROM tblFilm
WHERE FilmOscarWins >= 10
)
BEGIN
PRINT 'Double-digit Oscar winners found'
END
The following example creates two variables to hold:
The SQL then compares the two numbers, and prints a suitable message:
-- see if there are more Oscar-winners or long films
DECLARE @LongFilms int
DECLARE @OscarWinners int
-- find number of 3 hour plus films
SET @LongFilms = (
SELECT COUNT(*) FROM tblFilm
WHERE FilmRunTimeMinutes >=180
)
-- find number of films winning Oscars
SET @OscarWinners = (
SELECT COUNT(*) FROM tblFilm
WHERE FilmOscarWins > 0
)
-- show which is more
IF @LongFilms > @OscarWinners
PRINT 'More long films'
ELSE
IF @LongFilms <>
PRINT 'More Oscar winners'
ELSE
PRINT 'Same number of each'
If at all possible, use CASE WHEN instead of an IF to test multiple conditions, as it creates SQL which is much easier to read (and write). Here's how you could have written some of the queries above. First, the day of the week example:
-- print different messages according to
-- the day of the week
CASE DatePart(weekday,GetDate())
WHEN 1 THEN 'It''s the weekend!'
WHEN 7 THEN 'It''s the weekend!'
WHEN 6 THEN 'It''s Friday ...'
ELSE 'It''s a weekday ...'
END
You could write the last statement of the long films / Oscar winners query above as:
CASE
WHEN @LongFilms > @OscarWinners THEN 'More long films'
WHEN @LongFilms < @oscarwinners="">THEN 'More Oscar winners'
ELSE 'Same number of each'
END
In short, if you're using an IF statement, then there's a good chance you should be using CASE WHEN instead.
You can learn more about this topic on the following Wise Owl courses:
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.