SQL - CASE
SQL CASE: Conditional Logic in Queries
Section titled “SQL CASE: Conditional Logic in Queries”The SQL CASE Expression
Section titled “The SQL CASE Expression”The CASE expression is SQL’s way of handling if/then/else logic. It allows you to evaluate a list of conditions and return one of multiple possible result expressions. It does not control the flow of execution like an IF statement in procedural languages; instead, it is an expression that returns a value.
This makes it incredibly versatile for creating derived columns, custom sorting logic, and conditional updates, all within a single SQL statement.
Syntax: Simple vs. Searched CASE
Section titled “Syntax: Simple vs. Searched CASE”There are two forms of the CASE expression:
1. Simple CASE Expression
Section titled “1. Simple CASE Expression”This form compares an expression against a set of specific values.
CASE input_expression WHEN value1 THEN result1 WHEN value2 THEN result2 ... ELSE else_resultEND2. Searched CASE Expression
Section titled “2. Searched CASE Expression”This form evaluates a set of independent boolean conditions.
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE else_resultENDNote: The CASE statement processes conditions in order and stops at the first one that is met. The optional ELSE clause handles cases where no conditions are met; if omitted, NULL is returned.
Example: Using CASE in a SELECT Statement
Section titled “Example: Using CASE in a SELECT Statement”Let’s use a CUSTOMERS table to categorize customers into different tiers based on their SALARY.
CREATE TABLE CUSTOMERS( ID INT PRIMARY KEY, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(25), SALARY DECIMAL(18, 2));INSERT INTO CUSTOMERS VALUES(1, 'Ramesh', 32, 'Ahmedabad', 2000.00),(2, 'Khilan', 25, 'Delhi', 1500.00),(3, 'Kaushik', 23, 'Kota', 2000.00),(4, 'Chaitali', 25, 'Mumbai', 6500.00),(5, 'Hardik', 27, 'Bhopal', 8500.00),(6, 'Komal', 22, 'Hyderabad', 4500.00),(7, 'Muffy', 24, 'Indore', 10000.00);This query uses a searched CASE expression to create a new CustomerTier column.
SELECT NAME, SALARY, CASE WHEN SALARY >= 9000 THEN 'Platinum' WHEN SALARY >= 6000 THEN 'Gold' WHEN SALARY >= 3000 THEN 'Silver' ELSE 'Bronze' END AS CustomerTierFROM CUSTOMERS;Output
Section titled “Output”| NAME | SALARY | CustomerTier |
|---|---|---|
| Ramesh | 2000.00 | Bronze |
| Khilan | 1500.00 | Bronze |
| Kaushik | 2000.00 | Bronze |
| Chaitali | 6500.00 | Gold |
| Hardik | 8500.00 | Gold |
| Komal | 4500.00 | Silver |
| Muffy | 10000.00 | Platinum |
Using CASE with ORDER BY
Section titled “Using CASE with ORDER BY”CASE can create sophisticated sorting rules. For example, let’s sort customers by address, but ensure all customers from ‘Mumbai’ appear first.
SELECT NAME, ADDRESS, SALARYFROM CUSTOMERSORDER BY CASE WHEN ADDRESS = 'Mumbai' THEN 1 ELSE 2 END, -- Primary sort key NAME ASC; -- Secondary sort keyUsing CASE with GROUP BY
Section titled “Using CASE with GROUP BY”You can also group by the result of a CASE expression. This is useful for creating custom aggregation buckets.
SELECT CASE WHEN SALARY < 5000 THEN 'Entry Level' WHEN SALARY >= 5000 AND SALARY < 9000 THEN 'Mid Level' ELSE 'Senior Level' END AS SalaryBracket, COUNT(ID) AS NumberOfCustomers, AVG(SALARY) AS AverageSalaryFROM CUSTOMERSGROUP BY SalaryBracket;Output
Section titled “Output”| SalaryBracket | NumberOfCustomers | AverageSalary |
|---|---|---|
| Entry Level | 4 | 2500.00 |
| Mid Level | 2 | 7500.00 |
| Senior Level | 1 | 10000.00 |
Using CASE in an UPDATE Statement
Section titled “Using CASE in an UPDATE Statement”CASE is perfect for conditional updates. Let’s give raises based on current salary.
UPDATE CUSTOMERSSET SALARY = CASE WHEN SALARY < 2000 THEN SALARY * 1.15 -- 15% raise WHEN SALARY < 5000 THEN SALARY * 1.10 -- 10% raise ELSE SALARY * 1.05 -- 5% raise ENDWHERE ID > 0; -- A WHERE clause is always a good idea in UPDATEsVerification
Section titled “Verification”After running the update, you can select the data to see the new salaries.
SELECT NAME, SALARY FROM CUSTOMERS;Common Pitfalls and Best Practices
Section titled “Common Pitfalls and Best Practices”- Data Type Consistency: All
THENandELSEexpressions in aCASEstatement must return compatible data types. You cannot return a number in oneTHENand a string in another. - Don’t Forget
ELSE: Omitting theELSEclause will result inNULLfor any rows that don’t meet aWHENcondition. This can be intentional, but it’s often a source of bugs. Be explicit. - Order Matters: The
WHENconditions are evaluated in the order they are written. The first condition that evaluates to true determines the result, and subsequent conditions are ignored. NULLHandling: Comparisons withNULL(e.g.,WHEN my_column = NULL) are tricky. The correct way to check forNULLisWHEN my_column IS NULL.