CASE in SQL
Provides conditional logic in SQL queries, evaluating conditions and returning specified results based on matching conditions.
Syntax
Return type
CASE Function Example
What is CASE in SQL?
The CASE
statement in SQL allows you to implement conditional logic within queries. It evaluates conditions and returns a specified result based on the first matching condition. If no conditions match, an optional ELSE clause can provide a default value.
The CASE
statement is useful for categorizing data, conditional calculations, and dynamic result formatting. It is supported in SQL Server, MySQL, PostgreSQL, and Oracle.
The CASE
statement is a powerful tool in data transformation, reporting, and conditional processing.
Parameters:
expression (Simple CASE): Value to compare against WHEN clauses
condition (Searched CASE): Boolean conditions to evaluate
result: Value to return when condition is met
else_result (optional): Default value if no conditions match
Example Use Cases:
-- Grade calculation
-- Status mapping
-- Conditional aggregation
Notes:
Behavior: Returns NULL if no conditions match and no ELSE specified
Performance Considerations: Conditions evaluated in order
Version Info: Core SQL feature available in all DBMS
Deprecated/Recommended Alternatives: None, standard functionality
Error Handling:
Error: Type mismatch between result expressions
Recommendation: Ensure consistent return types
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
CASE
CASE WHEN col > 0 THEN 'Positive' ELSE 'Zero' END
Returns ELSE value or NULL
PostgreSQL
CASE
CASE WHEN col > 0 THEN 'Positive' ELSE 'Zero' END
Returns ELSE value or NULL
SQL Server
CASE
CASE WHEN col > 0 THEN 'Positive' ELSE 'Zero' END
Returns ELSE value or NULL
SQLite
CASE
CASE WHEN col > 0 THEN 'Positive' ELSE 'Zero' END
Returns ELSE value or NULL
BigQuery
CASE
CASE WHEN col > 0 THEN 'Positive' ELSE 'Zero' END
Returns ELSE value or NULL
Snowflake
CASE
CASE WHEN col > 0 THEN 'Positive' ELSE 'Zero' END
Returns ELSE value or NULL
Athena
CASE
CASE WHEN col > 0 THEN 'Positive' ELSE 'Zero' END
Returns ELSE value or NULL