← All lessons
SQL from zero · Lesson 9 of 10

Unique values and CASE

SELECT DISTINCT drops rows that are exactly the same as another, so each one appears once. The categories the shop sells:

SELECT DISTINCT category
FROM products
ORDER BY category;
Returns
category
--------
Books
Clothing
Garden
Outdoors
(4 rows)

With more than one column, DISTINCT keeps each different combination once. SELECT DISTINCT city, name would keep every customer, because no two have the same name and city.

CASE chooses a value for each row, like an "if" in a spreadsheet. It checks each WHEN in turn and uses the THEN of the first one that's true. ELSE covers everything else, and END closes it:

SELECT name, price,
  CASE
    WHEN price < 20 THEN 'low'
    WHEN price <= 50 THEN 'mid'
    ELSE 'high'
  END AS band
FROM products
ORDER BY price;
Returns
name        | price | band
------------+-------+-----
Sketchbook  | 9.75  | low
Pond net    | 12.5  | low
Field guide | 18    | low
Duck feeder | 24    | mid
Rain boots  | 40    | mid
Bird bath   | 45.5  | mid
Raincoat    | 59    | high
Binoculars  | 120   | high
(8 rows)

Because the first true WHEN wins, the second line doesn't need to say price >= 20: anything under 20 was already caught. If no WHEN is true and there's no ELSE, the result is NULL.

CASE can turn codes into words people understand, too:

SELECT id,
  CASE status WHEN 'shipped' THEN 'On its way' WHEN 'pending' THEN 'Not sent yet' ELSE 'Cancelled' END AS progress
FROM orders
WHERE customer_id = 3;
Returns
id  | progress
----+-----------
104 | Cancelled
110 | On its way
(2 rows)

That short form, CASE status WHEN 'shipped' …, compares one column with each value in turn.

Practice

The different cities customers live in, each once. (The missing city counts as one too.)

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

SELECT DISTINCT aEach different value of a once.
CASE WHEN c THEN x … ELSE y ENDThe x of the first true condition, or y.
CASE col WHEN v THEN x … ENDShort form: compare one column with each value.

The other AI and data engineering courses