IF Statement in SQL
In SQL, the IF
statement is used to conditionally execute a block of SQL statements. It allows you to perform different actions based on a specified condition.
Syntax
IF condition THEN
-- Statements to execute if condition is true
ELSE
-- Statements to execute if condition is false
END IF;
Example
IF EXISTS (SELECT * FROM employees WHERE department = 'Sales') THEN
SELECT 'Sales department exists';
ELSE
SELECT 'Sales department does not exist';
END IF;
This query checks if the 'Sales' department exists in the employees table and returns a message accordingly.
The IF
statement in SQL provides a way to add conditional logic to your queries, allowing you to control the flow of execution based on specified conditions.