CASE

The SQL CASE Expression

CASE goes through conditions and returns a value when the first condition is met (like if-then-else). If no condition is true, it returns the ELSE value, or NULL if there is no ELSE.

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ELSE result
END

Categorize Values

Example

Sort products into price bands:

SELECT ProductName, Price,
  CASE
    WHEN Price >= 15 THEN 'Premium'
    WHEN Price >= 8  THEN 'Standard'
    ELSE 'Budget'
  END AS PriceBand
FROM Products;

Result: 6 rows

ProductNamePricePriceBand
Basmati Rice 5kg12.5Standard
Green Tea 100 bags6.75Budget
Olive Oil 1L9.99Standard
Dark Chocolate3.49Budget
Espresso Beans 1kg18Premium
Almonds 500g8.25Standard

Simple CASE

Example

Compare one expression with several values:

SELECT FirstName, Department,
  CASE Department
    WHEN 'Sales'   THEN 'Revenue'
    WHEN 'Support' THEN 'Customer Care'
    ELSE 'Back Office'
  END AS Division
FROM Employees;

Result: 6 rows

FirstNameDepartmentDivision
RahulSalesRevenue
SaraSalesRevenue
DavidSalesRevenue
AnanyaSupportCustomer Care
JamesSupportCustomer Care
FatimaFinanceBack Office

CASE in ORDER BY and Aggregates

Example

Count orders above and below 100 in one query (a "pivot"):

SELECT SUM(CASE WHEN Amount >= 100 THEN 1 ELSE 0 END) AS LargeOrders,
       SUM(CASE WHEN Amount <  100 THEN 1 ELSE 0 END) AS SmallOrders
FROM Orders;

Result: 1 row

LargeOrdersSmallOrders
53

Example (ORDER BY)

Custom sort: show India first, then the rest alphabetically:

SELECT CustomerName, Country FROM Customers
ORDER BY CASE WHEN Country = 'India' THEN 0 ELSE 1 END, Country;

Result: 8 rows

CustomerNameCountry
Aarav TradersIndia
Delta MartIndia
Cedar & CoCanada
Fjord SuppliesNorway
Golden SpoonSingapore
Blue Harbor FoodsUK
Harbor LightsUK
Evergreen GrocersUSA