Sql Server If...else Statement

SQL Server: IF...ELSE Statement

In this post 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 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 'AODBA.com';
ELSE
   PRINT 'mySite.com';

GO

In this IF...ELSE statement example, we will print AODBA.com' if the variable @site_value is less than 25. Otherwise, we will print 'mySite.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 'AODBA.com';

GO

In this IF...ELSE statement example, we will print 'AODBA.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 'AODBA.com';
ELSE
BEGIN
   IF @site_value  50
      PRINT 'mySite.com';
   ELSE
      PRINT 'data.com';
END;

GO

In this nested IF...ELSE statement example, we will print 'AODBA.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 'mySite.com' if the variable @site_value is less than 50. Finally, if no other condition is met, 'data.com' will print.