T-SQL Tutorial

SQL IF statement


In SQL Server, the IF statement is a conditional statement used to execute a specific block of code based on a certain condition. The IF statement evaluates the expression and executes the SQL statements only if the expression returns TRUE. The basic syntax of the IF statement in SQL Server is as follows:


Syntax

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

The condition in the IF statement is any expression that evaluates to either true or false. If the condition is true, the block of code inside the BEGIN and END keywords is executed. If the condition is false, the block of code is skipped and the program continues to execute the next statement.


Example

For example, let's say we have a table called "Customers" with columns "FirstName", "LastName", and "Age". We can use the IF statement to update the age of a specific customer based on their last name:

IF EXISTS (SELECT * FROM Customers WHERE LastName = 'Smith')
BEGIN
UPDATE Customers
SET Age = 30
WHERE LastName = 'Smith'
END


In this example, the condition in the IF statement is the subquery that checks if there is a customer with the last name 'Smith' in the table. If the condition is true, the UPDATE statement inside the BEGIN and END keywords is executed, which updates the age of the customer with the last name 'Smith' to 30.

It's important to note that the IF statement in SQL Server can also be used with the ELSE keyword to execute a different block of code if the condition is false. Here's an example:

IF EXISTS (SELECT * FROM Customers WHERE LastName = 'Jones')
BEGIN
UPDATE Customers
SET Age = 35
WHERE LastName = 'Jones'
END
ELSE
BEGIN
INSERT INTO Customers (FirstName, LastName, Age)
VALUES ('John', 'Jones', 35)
END

In this example, if there is a customer with the last name 'Jones' in the table, their age is updated to 35. If there is no customer with that last name, a new record is inserted into the table with the first name 'John', last name 'Jones', and age 35.

Overall, the IF statement in SQL Server is a powerful tool that allows developers to execute different blocks of code based on certain conditions, making it a useful tool for building dynamic and flexible database applications.