Conditional Logic with CASE in SQL
Conditional Logic with CASE in SQL
The CASE
statement in SQL is a powerful tool that allows you to implement conditional logic within your queries. It works similarly to an IF-THEN-ELSE
statement in programming languages, allowing you to evaluate conditions and return specific values based on the results of those conditions. The CASE
statement can be used in SELECT
, UPDATE
, and ORDER BY
clauses, among others, making it highly versatile.
1. Understanding the CASE Statement
The CASE
statement evaluates a series of conditions and returns a value based on the first condition that evaluates to TRUE
. If no conditions are met, an optional ELSE
clause can provide a default value.
Syntax:
condition1, condition2, ...
: Conditions to be evaluated in sequence.result1, result2, ...
: Values to be returned if the corresponding condition isTRUE
.default_result
: A value to be returned if none of the conditions are met. This is optional.alias_name
: An alias for the result of theCASE
statement.
2. Basic Usage of CASE in a SELECT Statement
The most common use of CASE
is within a SELECT
statement to create new columns or modify existing ones based on conditional logic.
Example:
In this example:
The
CASE
statement categorizes employees' salaries intoHigh
,Medium
, andLow
based on the value of thesalary
column.The result of the
CASE
statement is given the aliassalary_category
.
Result:
Amit
Sharma
65000.00
High
Neha
Singh
45000.00
Medium
Ravi
Verma
35000.00
Low
In this output:
Employees are categorized into different salary ranges based on the conditions specified in the
CASE
statement.
3. Using CASE in WHERE Clause
You can also use the CASE
statement in the WHERE
clause to create dynamic filtering conditions.
Example:
In this example:
The
CASE
statement is used to apply different salary filters depending on the department.For employees in
Sales
, only those with a salary greater than 50,000 are selected.For employees in
IT
, the salary filter is set to 60,000.
4. Using CASE in ORDER BY Clause
The CASE
statement can also be used in the ORDER BY
clause to control the sorting of the result set based on conditions.
Example:
In this example:
The
CASE
statement determines the sorting order based on the department.If the department is
Sales
, the result set is sorted by salary.If the department is
IT
, the result set is sorted by first name.For other departments, the result set is sorted by last name.
5. Using CASE in UPDATE Statement
You can also use the CASE
statement in an UPDATE
query to conditionally update rows in a table.
Example:
In this example:
The
CASE
statement is used to update thebonus
column based on the employee's department.Employees in
Sales
receive a bonus of 10% of their salary, while those inIT
receive 15%. All other departments receive a 5% bonus.
6. Using Nested CASE Statements
You can nest CASE
statements inside each other to handle more complex conditions.
Example:
In this example:
The outer
CASE
statement evaluates the department, and the innerCASE
statements further categorize employees based on their salary within each department.
Result:
Amit
Sharma
65000.00
High Sales
Neha
Singh
55000.00
Low IT
Ravi
Verma
35000.00
Other Department
In this output:
Employees are categorized based on both their department and salary.
7. Handling NULL Values with CASE
CASE
can be used to handle NULL
values by explicitly checking for NULL
in the conditions.
Example:
In this example:
The
CASE
statement checks if thedepartment
column isNULL
and replaces it with "No Department" if it is.
Result:
Amit
Sharma
Sales
Sales
Neha
Singh
NULL
No Department
In this output:
NULL
values in thedepartment
column are replaced with "No Department".
8. Using CASE with Aggregations
You can use CASE
statements in combination with aggregation functions like SUM
, COUNT
, or AVG
to perform conditional aggregations.
Example:
In this example:
The
CASE
statement is used to separate the salaries into two categories (high_salary_total
andlow_salary_total
) based on whether they are above or below 50,000.The
SUM
function then aggregates the salaries within each category.
Result:
Sales
65000.00
0.00
IT
0.00
45000.00
In this output:
The salaries are aggregated separately based on the
CASE
statement conditions.
Conclusion
The CASE
statement in SQL is a versatile and powerful tool that allows you to implement conditional logic directly within your queries. Whether you need to create conditional columns, filter rows based on complex criteria, or apply dynamic sorting and updates, mastering the CASE
statement is essential for advanced SQL querying. With the ability to handle multiple conditions, work with NULL
values, and even nest CASE
statements, you can create highly flexible and dynamic SQL queries to meet a wide range of requirements.
This tutorial is brought to you by codes with pankaj.
Last updated