How to use the IF THEN ELSE Statement in SQL Server?

Transact-SQL comes rich with features allowing dynamic and robust data manipulation, and among these, the IF THEN ELSE statement serves as a pillar for decision-making within SQL Server code. This feature enables conditional execution of T-SQL statements, creating opportunities for more dynamic and responsive queries and data manipulation.

In this ultimate guide, to delve deep into the capabilities of the IF THEN ELSE statement, using a Sales table to provide real-world examples. Indeed, coditional statements are at the heart of algorithmics, which name comes from the famous Persian Mathematician Al-Khwarizmi.


Why and when use the T-SQL IF THEN ELSE statement?

The IF THEN ELSE statement in T-SQL serves as a critical tool for implementing conditional logic and decision-making within your SQL Server queries and applications. When needing to implement business rules directly within SQL queries, or when looking to make stored procedures and scripts more adaptable, the IF THEN ELSE statement becomes indispensable.

Essentially, to use this statement effectively means to write SQL code that is smarter, more efficient, and responsive to the data it interacts with.

Create the Sales table and insert data for the IF THEN ELSE examples

To illustrate the capabilities of the IF THEN ELSE statement, let’s create a Sales table that includes a column representing the amount of each sale. Another version of the sales table was used in another tutorial, as an XML sales table.

CREATE TABLE Sales (
  SalesID INT PRIMARY KEY,
  Amount FLOAT
);

To populate the Sales table with some sample data for demonstration:

INSERT INTO Sales (SalesID, Amount)
VALUES (1, 200.50), (2, 300.75), (3, 150.20);

Understand the basic syntax of IF THEN ELSE queries

The basic syntax for the IF THEN ELSE statement in T-SQL appears as follows:

IF condition
    BEGIN
        -- statements to execute if condition is TRUE
    END
ELSE
    BEGIN
        -- statements to execute if condition is FALSE
    END

Note: T-SQL doesn’t actually use the THEN keyword; we’ve included it in the title for readability and to align with other programming languages that use a similar construct.

Use a simple example to check the Sales amount

To begin with a straightforward example, checking if a sale exceeds a certain amount:

DECLARE @SalesAmount FLOAT;
SELECT @SalesAmount = Amount FROM Sales WHERE SalesID = 1;

IF @SalesAmount > 200
    BEGIN
        PRINT 'Large Sale';
    END
ELSE
    BEGIN
        PRINT 'Small Sale';
    END

To expect this example to output ‘Large Sale’ because the amount for SalesID = 1 is 200.50, which is greater than 200.

Use ELSE IF for multiple conditions

To use ELSE IF for handling multiple conditions:

DECLARE @SalesAmount FLOAT;
SELECT @SalesAmount = Amount FROM Sales WHERE SalesID = 1;

IF @SalesAmount > 300
    BEGIN
        PRINT 'Very Large Sale';
    END
ELSE IF @SalesAmount > 200
    BEGIN
        PRINT 'Large Sale';
    END
ELSE
    BEGIN
        PRINT 'Small Sale';
    END

We anticipate the output to be ‘Large Sale’ because the amount falls between 200 and 300.

How to implement a nested IF THEN ELSE query in T-SQL?

To nest IF THEN ELSE statements for more complex conditions:

DECLARE @SalesAmount FLOAT;
SELECT @SalesAmount = Amount FROM Sales WHERE SalesID = 1;

IF @SalesAmount >= 300
    BEGIN
        IF @SalesAmount >= 500
            BEGIN
                PRINT 'Extra Large Sale';
            END
        ELSE
            BEGIN
                PRINT 'Very Large Sale';
            END
    END
ELSE
    BEGIN
        PRINT 'Small or Large Sale';
    END

Conclusion on the T-SQL IF statement

The IF THEN ELSE statement in T-SQL serves as an indispensable tool for conditional logic and decision-making within SQL Server queries and applications. To master this feature allows for writing more dynamic, efficient, and robust SQL code.

Whether just starting with T-SQL or an experienced developer looking to up your game, understanding the IF THEN ELSE statement becomes crucial for writing intelligent, responsive database code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top