AdBlock Detected!
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.
SQL CASE |
|
SQL > Advanced SQL >
Case
CASE is used to provide if-then-else type of logic to SQL. There are two formats: The first is a Simple CASE expression, where we compare an expression to static values. The second is a Searched CASE expression, where we compare an expression to one or more logical conditions.
Key Takeaway: CASE brings conditional logic into SQL queries without needing to process data in application code. Use it to categorize values, apply different calculations, and pivot data all within a single query.
Simple CASE Expression SyntaxThe syntax for a simple CASE expression is: The ELSE clause is optional. Simple CASE Expression ExampleWe use the following table for our example. Table Store_Information
To multiply the sales amount from 'Los Angeles' by 2 and the sales amount from 'San Diego' by 1.5 while keeping the sales amount for other stores the same, we would use the following SQL statement using CASE: "New Sales" is the name given to the column with the CASE statement. This is an example of a simple CASE expression, because the conditions listed, 'Los Angeles' and 'San Diego', are static values. Result:
Searched CASE Expression SyntaxThe syntax for a searched CASE expression is: The ELSE clause is optional. "Condition" can consist of one or more logical statements. Searched CASE Expression ExampleWe use the same Store_Information above. If we want to define the status of a store's sale based on the following rules: We can use the following searched CASE expression: Result:
Note that a simple CASE expression is a special case of a searched CASE expression. As an example, the following two CASE expressions are identical: Simple CASE Expression: Searched CASE Expression: Frequently Asked QuestionsCan I use CASE in a WHERE clause?Yes. CASE can appear in WHERE to create complex conditional filters. However, it is more common to see CASE in the SELECT list. In WHERE, you would typically use: Can I use CASE in GROUP BY or ORDER BY?Yes. Using CASE in ORDER BY is common for custom sort logic. For example: What happens if no WHEN condition matches and there is no ELSE?The CASE expression returns NULL. Always include ELSE to handle unexpected values and avoid silent NULLs in your result set. Can CASE be used inside aggregate functions?Yes. This is a powerful pattern: |
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.