DbSchema Tutorial | SQL CASE EXPRESSION
SQL is a powerful language for managing and manipulating relational databases. Among its features is the CASE expression, which enables conditional logic directly within SQL. In this guide, we’ll explore this versatile tool in depth.
Introduction to SQL CASE Expression
The SQL CASE expression is a conditional construct, akin to “if-then-else” in many programming languages.
Syntax:
1 | CASE |
Example Database Table:
Consider a sample table Students
:
StudentID | Name | Grade |
---|---|---|
1 | Alice | 85 |
2 | Bob | 60 |
3 | Carol | 72 |
4 | Dave | 90 |
To categorize students based on their grades:
1 | SELECT Name, |
Result:
Name | Performance |
---|---|
Alice | Excellent |
Bob | Average |
Carol | Good |
Dave | Excellent |
Explanation:
Each student’s grade is assessed, and they are labeled accordingly.
The CASE Statement and Comparison Operator
Example:
Using the Students
table, we can label students with exactly 85 as ‘Perfect’:
1 | SELECT Name, |
Result:
Name | Label |
---|---|
Alice | Perfect |
Bob | Other |
Carol | Other |
Dave | Other |
Explanation:
Here, only Alice has a grade of 85, so she’s labeled ‘Perfect’. The rest are designated as ‘Other’.
Using the CASE Statement with the ORDER BY Clause
Example:
1 | SELECT Name, Grade, |
Result:
Name | Grade | Performance |
---|---|---|
Alice | 85 | Excellent |
Dave | 90 | Excellent |
Carol | 72 | Good |
Bob | 60 | Average |
Explanation:
Students are sorted with ‘Excellent’ ones at the top, followed by ‘Good’, and then ‘Average’.
The CASE Statement with the GROUP BY Clause
Example:
1 | SELECT |
Result:
Performance | NumberOfStudents |
---|---|
Excellent | 2 |
Good | 1 |
Average | 1 |
Explanation:
Here, students are grouped by their performance level. We see that there are two ‘Excellent’ students, one ‘Good’, and one ‘Average’.
Updating Records with the CASE Statement
Modify data conditionally using CASE.
Example:
Give a bonus of 5 points to students with ‘Average’ performance:
1 | UPDATE Students |
This will update Bob’s grade to 65.
Inserting Records Using the CASE Statement
Insert data with conditional values.
Example:
If a new student has a grade of 88, label them:
1 | INSERT INTO Students (Name, Grade, Label) |
Eve will be labeled ‘Excellent’.
CASE in Aggregate Functions
Example:
1 | SELECT AVG( |
Result:
AvgExcellent |
---|
87.5 |
Explanation:
The average grade of ‘Excellent’ students (Alice and Dave) is calculated to be 87.5.
Preventing Divide by Zero Errors
CASE can prevent division by zero.
Example:
If we had a table Sales
with columns TotalSales
and NumberOfTransactions
, to find the average sale:
1 | SELECT TotalSales / |
This ensures no division by zero occurs.
Searched CASE Statements
Example:
1 | SELECT Name, |
Result:
Name | Label |
---|---|
Alice | Almost Excellent |
Bob | Other |
Carol | Other |
Dave | Other |
Explanation:
Alice, with a grade between 80 and 85, is labeled ‘Almost Excellent’. The others are labeled ‘Other’.
Nested CASE Statements
Example:
1 | SELECT Name, |
Result:
Name | Label |
---|---|
Alice | Perfect |
Bob | Even Grade |
Carol | Odd Grade |
Dave | Excellent |
Explanation:
Alice, with a grade of 85, is labeled ‘Perfect’. Dave, with a grade above 85, is ‘Excellent’. Bob’s grade is even, hence ‘Even Grade’, and Carol’s grade is odd, making her ‘Odd Grade’.
Deleting Records Using CASE
Though not common, CASE can aid in deleting records.
Example:
Delete students labeled ‘Average’:
1 | DELETE FROM Students |
Bob will be removed from the table.
Common Mistakes
- Forgetting the
END
keyword. - Using CASE without ELSE can result in NULL values.
- Over-nesting can make code hard to read.
Frequently Asked Questions
Q: Can CASE be used with non-numeric data?
A: Yes, it can work with strings, dates, etc.
Q: Is CASE the only conditional expression in SQL?
A: No, there are other functions like IIF in some databases.
Practice Questions
- Write a SQL query to label students with grades above 90 as ‘Topper’.
- How would you use the CASE statement to categorize sales in a table into ‘Low’, ‘Medium’, and ‘High’ based on amount?
- Use a nested CASE statement to label items in a store as ‘Perishable’ or ‘Non-Perishable’, and within ‘Non-Perishable’, further categorize as ‘Electronic’ or ‘Other’.
We hope this comprehensive guide on the SQL CASE expression aids in your understanding. The versatility of the CASE expression allows for a wide range of conditional logic directly within SQL. Practice is key to mastery, so be sure to experiment with the examples provided.
Happy querying!!