Case
CASE
can be used to create categories or group data based on specific conditions. This is valuable when dealing with numerical or textual data that needs to be segmented into different groups or categories for analysis, reporting, or visualization purposes.
Here is a database OrderDetails we’ll use:
OrderDetailID | OrderID | ProductID | Quantity |
---|---|---|---|
1 | 10248 | 11 | 12 |
2 | 10248 | 42 | 10 |
3 | 10248 | 72 | 5 |
4 | 10249 | 14 | 9 |
5 | 10249 | 51 | 40 |
Basic
SELECT OrderID, Quantity,
CASE > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
WHEN Quantity 'The quantity is under 30'
ELSE
END AS QuantityText FROM OrderDetails;
Output (partial):
Order ID | Quantity | QuantityText |
---|---|---|
10254 | 21 | The quantity is under 30 |
10255 | 20 | The quantity is under 30 |
10255 | 35 | The quantity is greater than 30 |
10255 | 25 | The quantity is under 30 |
10255 | 30 | The quantity is 30 |
Basic As
- You can always save the results of the
CASE
query in anALIAS
- Here we’ll clean the data and save in a temporary object: cleaned_name
SELECT
Customer_id,
CASE='Tnoy' THEN'Tony'
WHEN first_name = 'Tango' THEN 'Taco'
WHEN first_name
ELSE first_name END AS cleaned_name
Order Unless
- The following will
ORDER BY
the customers by City - In the
CASE
City isNULL
then it willORDER BY
Country - Use Customers table
CustomerName | City | Country |
---|---|---|
Drachenblut Delikatessend | Aachen | Germany |
Rattlesnake Canyon Grocery | Albuquerque | USA |
Old World Delicatessen | Anchorage | USA |
Vaffeljernet | Århus | Denmark |
Galería del gastrónomo | Barcelona | Spain |
SELECT CustomerName, City, Country
FROM CustomersBY (CASE
ORDER NULL THEN Country
WHEN City is
ELSE City END);