CASE
expression in SQL is used to implement conditional logic in queries. It allows you to perform different actions based on specific conditions. The CASE
expression is similar to the IF-THEN-ELSE
logic in programming languages and is useful for creating derived columns, categorizing data, and applying conditional formatting.
CASE
expression allows you to implement conditional logic in SQL queries.WHEN
clauses.ELSE
clause can be used to specify a default value if none of the conditions are met.SELECT
, UPDATE
, and ORDER BY
clauses to create derived columns, categorize data, or apply conditional sorting.condition1, condition2, ...
: The conditions to evaluate.result1, result2, ...
: The result to return if the corresponding condition is true.default_result
: The result to return if none of the conditions are true (optional).Employees
that stores employee details.
Table: Employees
EmployeeID | Name | City | State | Salary |
---|---|---|---|---|
1 | Anand | Chennai | Tamil Nadu | 50000 |
2 | Bala | Coimbatore | Tamil Nadu | 60000 |
3 | Kavitha | Karaikal | Puducherry | 55000 |
4 | Raj | Madurai | Tamil Nadu | 70000 |
5 | Kumar | Trichy | Tamil Nadu | 45000 |
Name | Salary | SalaryCategory |
---|---|---|
Anand | 50000 | Medium |
Bala | 60000 | Medium |
Kavitha | 55000 | Medium |
Raj | 70000 | High |
Kumar | 45000 | Low |
CASE
expression in the ORDER BY
clause to apply conditional sorting.
To sort employees by salary category (High, Medium, Low):
Name | Salary |
---|---|
Raj | 70000 |
Anand | 50000 |
Bala | 60000 |
Kavitha | 55000 |
Kumar | 45000 |
CASE
expression in the UPDATE
statement to apply conditional updates.
To update the salary of employees based on their current salary:
Students
that stores student details.
Students
StudentID | Name | City | State | Percentage |
---|---|---|---|---|
1 | Ram | Chennai | Tamil Nadu | 92 |
2 | Karthik | Coimbatore | Tamil Nadu | 88 |
3 | David | Bangalore | Karnataka | 95 |
4 | Kannan | Karaikal | Puducherry | 91 |
5 | Siva | Madurai | Tamil Nadu | 89 |
Name | Percentage | Grade |
---|---|---|
Ram | 92 | A |
Karthik | 88 | B |
David | 95 | A |
Kannan | 91 | A |
Siva | 89 | B |
CASE
expression allows you to implement conditional logic in SQL queries.SELECT
, UPDATE
, and ORDER BY
clauses to create derived columns, categorize data, or apply conditional sorting.WHEN
clauses, and an optional ELSE
clause can provide a default value.CASE
expression is useful for creating dynamic and flexible queries.