![]() |
VOOZH | about |
The SQL CASE statement is used to add conditional logic inside SQL queries. It checks conditions one by one and returns a value as soon as a matching condition is found.
Example: First, we create a demo SQL table, on which we use the CASE statement.
Query:
SELECT CustomerID, CustomerName, Age,
CASE Age
WHEN 21 THEN 'Young Adult'
WHEN 22 THEN 'Adult'
WHEN 23 THEN 'Mid Adult'
WHEN 24 THEN 'Senior Adult'
ELSE 'Unknown'
END AS AgeGroup
FROM Customer;
Output:
Syntax:
CASE case_value
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE result
END
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
The SQL CASE statement allows conditional logic in queries by returning different values based on specified conditions.
This demonstrates how conditional rules are applied to return a nationality based on each customerβs country.
Query:
SELECT CustomerName, Country, Age,
CASE
WHEN Country = 'United Kingdom' THEN 'British'
WHEN Country = 'Australia' THEN 'Australian'
WHEN Country = 'Japan' THEN 'Japanese'
WHEN Country = 'Austria' THEN 'Austrian'
WHEN Country = 'Spain' THEN 'Spanish'
ELSE 'Other'
END AS Nationality
FROM Customer;
Output:
We can add multiple conditions in the CASE statement by using multiple WHEN clauses.
Query:
SELECT CustomerName, Age,
CASE
WHEN Age = 21 THEN 'Age is 21'
WHEN Age = 22 THEN 'Age is 22'
WHEN Age > 22 THEN 'Age is greater than 22'
ELSE 'Age is below 21'
END AgeDescription
FROM Customer;
Output:
The Customer table contains fields like CustomerID, CustomerName, LastName, Country, Age and Phone and its data can be arranged using the ORDER BY clause together with the CASE statement.
Query:
SELECT
CustomerName,
Country,
CASE
WHEN Country = 'Japan' THEN 0
ELSE 1
END AS SortPriority
FROM Customer
ORDER BY SortPriority, Country;
Output:
π Screensho