SQL Server: IF…ELSE Statement
This SQL Server tutorial explains how to use the IF…ELSE statement in SQL Server (Transact-SQL) with syntax and examples.
Description
In SQL Server, the IF…ELSE statement is used to execute code when a condition is TRUE, or execute different code if the condition evaluates to FALSE.
Syntax
The syntax is for the IF…ELSE statement in SQL Server (Transact-SQL) is:
IF condition {...statements to execute when condition is TRUE...} [ ELSE {...statements to execute when condition is FALSE...} ]
- ELSE
- Optional. You would use the ELSE condition when you want to execute a set of statements when the IF condition evaluated to FALSE (ie: the condition was not met).
Note
- Within the IF…ELSE statement, the ELSE condition is optional.
- There is no ELSE IF condition in the IF…ELSE statement. Instead, you will have to nest multiple IF…ELSE statements to achieve the desired effect.
Example – IF…ELSE Statement
Let’s look at an example of how to use the IF…ELSE statement in SQL Server (Transact-SQL).
For example:
DECLARE @site_value INT; SET @site_value = 15; IF @site_value < 25 PRINT 'TechOnTheNet.com'; ELSE PRINT 'CheckYourMath.com'; GO
In this IF…ELSE statement example, we will print TechOnTheNet.com’ if the variable @site_value is less than 25. Otherwise, we will print ‘CheckYourMath.com’.
Example – No ELSE condition
Since the ELSE condition is optional, you are not required to include the ELSE condition in the IF…ELSE statement in SQL Server.
Let’s look at an example of how to exclude the ELSE condition from the IF…ELSE statement in SQL Server (Transact-SQL).
For example:
DECLARE @site_value INT; SET @site_value = 15; IF @site_value < 25 PRINT 'TechOnTheNet.com'; GO
In this IF…ELSE statement example, we will print ‘TechOnTheNet.com’ if the variable @site_value is less than 25. There is no ELSE condition in this IF…ELSE statement example.
Example – Nested IF…ELSE Statements
Since we can’t write an ELSE IF condition within the IF…ELSE statement, we need to nest multiple IF…ELSE statements instead.
Let’s look at an example of how to nest multiple IF…ELSE statements in SQL Server (Transact-SQL).
For example:
DECLARE @site_value INT; SET @site_value = 15; IF @site_value < 25 PRINT 'TechOnTheNet.com'; ELSE BEGIN IF @site_value < 50 PRINT 'CheckYourMath.com'; ELSE PRINT 'BigActivities.com'; END; GO
In this nested IF…ELSE statement example, we will print ‘TechOnTheNet.com’ if the variable @site_value is less than 25.
Otherwise, the first ELSE condition will be executed. Within this ELSE condition, there is a nested IF…ELSE statement that will print ‘CheckYourMath.com’ if the variable @site_value is less than 50. Finally, if no other condition is met, ‘BigActivities.com’ will print.