Wednesday, December 18, 2024

SQL CASE Keyword

 The CASE keyword in SQL is used to perform conditional logic, similar to an IF-THEN-ELSE structure in programming. It allows you to return different values based on conditions or expressions. There are two forms of CASE in SQL:

1. Simple CASE Expression:

This form evaluates a single expression and compares it with different values.

Syntax:

SELECT column_name,
       CASE column_name
           WHEN value1 THEN result1
           WHEN value2 THEN result2
           ELSE result3
       END
FROM table_name;

Example:

SELECT first_name,
       last_name,
       CASE gender
           WHEN 'M' THEN 'Male'
           WHEN 'F' THEN 'Female'
           ELSE 'Other'
       END AS gender_description
FROM employees;

In this example, the gender column is checked, and depending on the value, it returns 'Male', 'Female', or 'Other'.

2. Search CASE Expression:

This form allows you to use more complex conditions by evaluating each condition independently.

Syntax:

SELECT column_name,
       CASE
           WHEN condition1 THEN result1
           WHEN condition2 THEN result2
           ELSE result3
       END
FROM table_name;

Example:

SELECT first_name,
       last_name,
       CASE 
           WHEN salary > 50000 THEN 'High Salary'
           WHEN salary BETWEEN 30000 AND 50000 THEN 'Average Salary'
           ELSE 'Low Salary'
       END AS salary_range
FROM employees;

Here, the salary is checked using different conditions to categorize it into different salary ranges.

Key Points:

  • The CASE statement returns a result based on conditions and can be used in SELECT, UPDATE, DELETE, or ORDER BY clauses.
  • ELSE is optional; if no conditions are met and no ELSE clause is provided, NULL will be returned.
  • CASE is evaluated sequentially, and once a condition matches, it stops checking further conditions.

Let me know if you'd like to see more examples or have other questions!

No comments:

Post a Comment