How To Use If Else Statement In SQL

In this article, we will learn how to use the If-Else statement in SQL.

In SQL, the If-Else statement executes a block of code if a specified condition is true. If the condition is false, else block of code can be executed.

The If-Else statement is a part of SQL’s conditional Statements. Conditional Statements are used to perform different actions based on different conditions in SQL.

Syntax

IF <Condition>
BEGIN
    -- Statement block executes when the Condition is TRUE.
END
ELSE
BEGIN
    -- Statement block executes when the Condition is FALSE.
END

Example

If the number of students is under 100 in the StudentInfo table the subsequent statement would print ex. ‘Number of Students: 67’ else it would print ‘Number of Students: >= 100’

BEGIN
    DECLARE @count INT = 0;
 
    SELECT @count = count(*) FROM StudentInfo;
 
    IF @count < 100
    BEGIN
        PRINT 'Number of Students: ' + CAST(@count AS VARCHAR);
    END
    ELSE
    BEGIN
      PRINT 'Number of Students: >= 100';        
    END
END

 

Also, check How To Write Insert Into Select Query In SQL

Submit a Comment

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

Subscribe

Select Categories