DevPath · Learn to code ESPTEN

Advanced SQL: windows, views and CASE

Conditional logic with CASE

The CASE expression

CASE is SQL's "if/else": it evaluates conditions in order and returns the value of the first one that holds. It is an expression, so it can go anywhere a value fits: in the SELECT, in the ORDER BY, etc.

SELECT
  name,
  price,
  CASE
    WHEN price < 50  THEN 'cheap'
    WHEN price < 200 THEN 'medium'
    ELSE 'expensive'
  END AS tier
FROM products;

Shorthand form

When you compare the same column against specific values, there is a shorter form:

SELECT name,
  CASE category
    WHEN 'peripherals' THEN 'accessory'
    WHEN 'displays'    THEN 'visualization'
    ELSE 'other'
  END AS type
FROM products;

Mind the order of the conditions. Since the first one that holds wins, the more specific branches must come before the more general ones.

Examples

Classify prices into readable tiers

SELECT name, price,
  CASE
    WHEN price < 50  THEN 'cheap'
    WHEN price < 200 THEN 'medium'
    ELSE 'expensive'
  END AS tier
FROM products
ORDER BY price;
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Window functions →