Friday, January 17, 2025
HomeProgrammingHow do I Create an IF-THEN-ELSE Statement in SQL?

How do I Create an IF-THEN-ELSE Statement in SQL?

In SQL, you can use CASE expressions to implement IF-THEN-ELSE logic. A CASE expression can be used within a SELECT, WHERE, ORDER BY, or other clauses to evaluate conditions and return specific results.

General Syntax

Simple CASE Expression:

This compares one expression to multiple possible values:

sql
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE default_result
END

Searched CASE Expression:

This allows more complex, condition-based logic:

sql
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END

Examples

1. Using in a SELECT Clause

To categorize values based on conditions:

sql
SELECT
employee_name,
salary,
CASE
WHEN salary > 5000 THEN 'High'
WHEN salary BETWEEN 3000 AND 5000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;
  • Explanation: Each row is evaluated, and the salary_category is assigned based on the employee’s salary.

2. Using in a WHERE Clause

To filter rows dynamically:

sql
SELECT *
FROM orders
WHERE
CASE
WHEN order_status = 'Pending' THEN shipment_date > CURRENT_DATE
ELSE shipment_date <= CURRENT_DATE
END;
  • Explanation: The WHERE clause dynamically applies different conditions based on the order_status.

3. Using in an UPDATE Statement

To update values conditionally:

sql
UPDATE employees
SET bonus =
CASE
WHEN performance_rating = 'A' THEN 1000
WHEN performance_rating = 'B' THEN 500
ELSE 0
END;
  • Explanation: Updates the bonus column based on the performance_rating.

Key Notes

  1. Order of Conditions:
    • Conditions are evaluated in the order they appear.
    • The first condition that evaluates to TRUE determines the result.
  2. Default with ELSE:
    • Always include an ELSE to handle cases where none of the conditions match.
    • If ELSE is omitted and no conditions are met, the result will be NULL.
  3. Portability:
    • The CASE expression is standard SQL and works across most databases (e.g., MySQL, PostgreSQL, SQL Server, Oracle).
See also  How to Install Java

Using CASE, you can replicate IF-THEN-ELSE logic flexibly in SQL queries.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x