SQLite CASE Expression
The CASE Expression
CASE goes through conditions, and returns a value when the first condition is true, like an if, then, else statement. If no condition is true, it returns the value in the ELSE part. Without ELSE, it returns NULL.
Example
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN 'More than 30'
WHEN Quantity = 30 THEN 'Exactly 30'
ELSE 'Less than 30'
END AS QuantityText
FROM OrderDetails;
Try it Yourself »
Compare One Value
When every condition compares the same column, you can write the column once, after CASE:
Example
SELECT ProductName,
CASE CategoryID
WHEN 1 THEN 'Beverages'
WHEN 2 THEN 'Condiments'
ELSE 'Other'
END AS Category
FROM Products;
Try it Yourself »
CASE in ORDER BY
CASE can be used in ORDER BY too. This example sorts the customers by country, but puts the customers from Germany first:
Example
SELECT CustomerName, Country
FROM Customers
ORDER BY
CASE WHEN Country = 'Germany' THEN 0 ELSE 1 END,
Country;
Try it Yourself »
The IIF() Function
For a simple choice between two values, SQLite has the IIF() function. It returns the second argument if the condition is true, and the third argument if it is not:
Example
SELECT ProductName, Price,
IIF(Price > 50, 'Expensive', 'Cheap')
FROM Products;
Try it Yourself »
Note: IIF() works in SQLite 3.32.0 and later.