How to Use If Else Condition in SQL
In SQL, the IF ELSE condition is a powerful tool that allows you to perform conditional logic within your queries. This feature is particularly useful when you need to execute different actions based on the evaluation of a condition. In this article, we will explore how to use the IF ELSE condition in SQL and provide examples to illustrate its usage.
The basic syntax for the IF ELSE condition in SQL is as follows:
“`sql
IF condition THEN
— execute this block of code if the condition is true
ELSE
— execute this block of code if the condition is false
END IF;
“`
To understand how this works, let’s consider an example. Suppose you have a table named `employees` with columns `employee_id`, `name`, and `salary`. You want to update the `salary` of each employee based on their performance. If an employee’s performance is ‘Excellent’, you want to increase their salary by 10%; if their performance is ‘Good’, increase it by 5%; and if their performance is ‘Average’ or below, leave it unchanged.
Here’s how you can achieve this using the IF ELSE condition:
“`sql
UPDATE employees
SET salary = salary 1.1
WHERE performance = ‘Excellent’;
UPDATE employees
SET salary = salary 1.05
WHERE performance = ‘Good’;
UPDATE employees
SET salary = salary
WHERE performance = ‘Average’ OR performance = ‘Poor’;
“`
While the above queries achieve the desired result, they can be simplified using the IF ELSE condition. Here’s the modified query:
“`sql
UPDATE employees
SET salary = CASE
WHEN performance = ‘Excellent’ THEN salary 1.1
WHEN performance = ‘Good’ THEN salary 1.05
ELSE salary
END;
“`
In this example, the CASE statement is used to replace the multiple IF ELSE conditions. The CASE statement evaluates each condition in the order they are written and returns the result of the first true condition.
The IF ELSE condition can also be used in other SQL statements, such as SELECT, INSERT, and DELETE. For instance, let’s say you want to select all employees whose salary is above a certain threshold and display a custom message for those who are not:
“`sql
SELECT employee_id, name,
CASE
WHEN salary > 50000 THEN ‘Salary above threshold’
ELSE ‘Salary below threshold’
END as salary_status
FROM employees;
“`
In this query, the CASE statement is used to determine the salary status of each employee based on their salary value.
In conclusion, the IF ELSE condition in SQL is a versatile tool that can help you perform conditional logic within your queries. By using the CASE statement or nested IF ELSE conditions, you can execute different actions based on the evaluation of a condition, making your SQL queries more dynamic and powerful.