How to make a SQL "IF-THEN-ELSE" statement

67    Asked by AbhinayanVerma in SQL Server , Asked on Aug 24, 2025

How can you write an IF-THEN-ELSE statement in SQL? What syntax and functions are available to handle conditional logic within your queries?

When working with databases, you often need conditional logic to control what data gets returned. A common question developers ask is: “How do I write an IF-THEN-ELSE statement in SQL?” While SQL doesn’t have a direct IF-THEN-ELSE command like traditional programming languages, it provides functions and expressions that achieve the same result.

Using CASE Statement (Most Common):

 The CASE expression is the standard way to handle conditional logic in SQL.

 SELECT 
    employee_name,
    salary,
    CASE
        WHEN salary > 50000 THEN 'High Salary'
        ELSE 'Standard Salary'
    END AS salary_category
FROM employees;

  Here, the query checks each employee’s salary and categorizes it accordingly.

Using IF Function (MySQL specific):

 In MySQL, you can also use the IF() function directly.

 SELECT 
    employee_name,
    IF(salary > 50000, 'High Salary', 'Standard Salary') AS salary_category
FROM employees;

  This works like a shorthand IF-THEN-ELSE.

Stored Procedures with IF-ELSE:

 Inside stored procedures, you can use IF...ELSE blocks to control flow:

 IF salary > 50000 THEN
    SET category = 'High Salary';
ELSE
    SET category = 'Standard Salary';
END IF;

 Key Takeaway:

  • Use CASE when writing queries (works in all SQL databases).
  • Use IF() in MySQL for simpler conditions.
  • Use IF...ELSE inside stored procedures for advanced logic.

This way, SQL lets you implement conditional checks just like an IF-THEN-ELSE structure in programming.



Your Answer

Interviews

Parent Categories