T-SQL Tutorial

SQL ELSE statement


In SQL Server, the ELSE statement is used in conjunction with the IF statement to define a block of code that is executed when a condition is not met. The ELSE statement is optional and is used to handle cases where the IF statement evaluates to false.

The syntax for using the ELSE statement in SQL Server is as follows:


Syntax

IF condition
BEGIN
-- code to be executed if the condition is true
END
ELSE
BEGIN
-- code to be executed if the condition is false
END

In this syntax, the condition is the expression that is evaluated to determine whether the code within the BEGIN and END blocks is executed or not.


Example

For example, let's say we have a table called Employees with columns EmployeeID, FirstName, LastName, and Salary. We want to update the salary of employees with a salary less than 50000 by 10% and employees with a salary greater than or equal to 50000 by 5%. We can use the IF...ELSE statement to accomplish this as follows:

UPDATE Employees
SET Salary = CASE
WHEN Salary lt; 50000 THEN Salary * 1.1
ELSE Salary * 1.05
END


In this example, we're using a CASE statement inside the SET clause to evaluate the salary of each employee and determine whether to increase it by 10% or 5%. If the salary is less than 50000, the WHEN clause is true and the salary is increased by 10%. If the salary is greater than or equal to 50000, the WHEN clause is false and the salary is increased by 5%.

The ELSE statement is an important component of the IF statement in SQL Server, as it allows for the execution of code when the condition specified in the IF statement is false. This can be useful in a variety of scenarios where conditional logic is required, such as updating data in a database or displaying different content on a web page based on user input.