CASE Statement

Purpose: The CASE statement allows for conditional logic within SQL queries, enabling you to return different values based on certain conditions.

Syntax:

SELECT column1,
       CASE
         WHEN condition1 THEN result1
         WHEN condition2 THEN result2
         ELSE result_default
       END AS alias
FROM table_name;

Example

SELECT first_name, salary,
CASE
WHEN salary < 50000 THEN 'Low'
WHEN salary BETWEEN 50000 AND 100000 THEN 'Medium'
ELSE 'High'
END AS salary_category
FROM employees;

Explanation: This categorizes employees’ salaries as ‘Low’, ‘Medium’, or ‘High’ based on defined salary ranges.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *