IF ELSE Control of flow statements

The IF ELSE statements are one of the most frequently used statement within SQL and control of

flow statements are one of the core statements within any programing language. Once you have

understood the concept you can easily make powerful scripts.

An IF statement is a check to see whether a condition is TRUE and is used in hundreds of different

scenarios such as checking whether an object exists, checking data for a value…… I always liken the

IF statement to checking your fridge for your favourite meal and if its there you eat otherwise you

check out all your other options.

The below is a simple script which tests to see whether I have the AdventureWorks2012 database.

IF EXISTS (SELECT * FROM sys.databases

WHERE name = 'AdventureWorks2012' )

PRINT 'AdventureWorks2012 is installed'

The result you will get is below.

AdventureWorks2012 is installed


The query checks whether the AdventureWorks2012 returns a value or is TRUE from my query and

then runs the PRINT command to confirm the value was returned as I expected.

You can make the IF statement more powerful by adding the ELSE statement. The ELSE Statement is

used as we often don’t just want to check if a statement is TRUE but also want to produce an action if its false.

DECLARE @TestValue int

SET @TestValue = 1

IF @TestValue >1


PRINT 'The Test value is greater than 1'



PRINT 'The Test value is less than or equal to 1'

The result you will get is below.

The Test value is less than or equal to 1


Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: