Want to add decision-making capabilities to your W3 SQL queries? The SQL CASE statement is an excellent tool for this purpose. It allows you to test multiple conditions and specify an action for each true condition, making your queries more dynamic and efficient. Let's explore this versatile statement and see how it can enhance your SQL skills.

Before diving into the details, let's briefly look at why you might need a CASE statement. Imagine you have a database of student grades, and you want to categorize them into 'Excellent', 'Good', or 'Needs Improvement' based on their scores. A CASE statement would be perfect for this task, as it lets you set different outcomes for different conditions.

Understanding the SQL CASE Statement
The basic syntax of the SQL CASE statement is as follows:

| Syntax |
|---|
CASE condition |
WHEN condition THEN result |
ELSE result |
END |
Let's break it down:

- CASE condition: This is the main condition that will be tested. If it's true, the CASE statement will evaluate the subsequent WHEN conditions.
- WHEN condition THEN result: If the condition is true, the corresponding result will be returned. You can have multiple WHEN conditions.
- ELSE result: If none of the WHEN conditions are true, the ELSE result will be returned.
- END: This marks the end of the CASE statement.
Simple CASE Statement
A simple CASE statement tests only one condition. Here's an example:

SELECT score,
CASE score
WHEN 90 THEN 'Excellent'

WHEN 70 THEN 'Good'
ELSE 'Needs Improvement'




















END AS grade
The above query will return student scores and their corresponding grades based on the given conditions.
Searched CASE Statement
A searched CASE statement tests multiple conditions. In this type, you specify the conditions and their corresponding results after the CASE keyword, like this:
SELECT score,
CASE
WHEN score >= 90 THEN 'Excellent'
WHEN score >= 70 THEN 'Good'
ELSE 'Needs Improvement'
END AS grade
The results of a searched CASE statement are determined by the order of the WHEN conditions, so you can decide which result should take precedence.
Nested CASE Statements
Just like functions, CASE statements can be nested to perform more complex evaluations. Here's an example of a nested CASE statement:
SELECT score, subject,
CASE subject
WHEN 'Math' THEN
CASE score
WHEN 100 THEN 'Perfect'
ELSE 'Excellent'
END
WHEN 'Science' THEN
CASE score
WHEN 90 THEN 'Excellent'
ELSE 'Good'
END
ELSE 'Needs Improvement'
END AS grade
In this example, the outer CASE statement tests the subject, and the inner CASE statement evaluates the score based on the subject.
Mastering the SQL CASE statement opens up numerous possibilities for enhancing your queries. It allows you to add decision-making capabilities, improve performance by reducing the use of functions, and even simplify complex logic. So, start practicing and incorporating this versatile tool into your SQL arsenal. Happy coding!