Chapter 13 · Lesson 1 of 4

CASE WHEN Basics

Use a searched CASE WHEN expression to label each row, such as sorting orders into small, medium, and large buckets based on their amount.

CASE is SQL's if/else. It checks conditions and returns a value for each row, so you can add a new label column without changing the table.

The most common form is the searched CASE: a list of WHEN condition THEN value branches, an optional ELSE, and END.

SELECT
  order_id,
  amount,
  CASE
    WHEN amount < 50 THEN 'small'
    WHEN amount < 200 THEN 'medium'
    ELSE 'large'
  END AS size_band
FROM shop_orders
WHERE amount IS NOT NULL

Each CASE expression produces one value per row. Give it an alias with AS so the result column has a readable name.

The WHERE amount IS NOT NULL filter keeps the order without an amount out of this first example. The next lesson shows why missing values need special care inside CASE.

Sample data

This lesson loads the shop_orders table (10 rows, one missing amount) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for shop_orders
CREATE OR REPLACE TABLE shop_orders (
    order_id INTEGER,
    customer VARCHAR,
    amount DECIMAL(10,2),
    status VARCHAR,
    country VARCHAR,
    order_date DATE
  );

INSERT INTO shop_orders VALUES
    (1, 'Ava', 45.00, 'shipped', 'US', '2024-03-01'),
    (2, 'Ben', 180.00, 'shipped', 'DE', '2024-03-02'),
    (3, 'Cara', 95.50, 'pending', 'US', '2024-03-03'),
    (4, 'Dan', 320.00, 'cancelled', 'FR', '2024-03-04'),
    (5, 'Eli', 12.99, 'shipped', 'DE', '2024-03-05'),
    (6, 'Fay', 150.00, 'pending', 'US', '2024-03-06'),
    (7, 'Gus', 99.99, 'shipped', 'FR', '2024-03-07'),
    (8, 'Hana', 510.00, 'shipped', 'US', '2024-03-08'),
    (9, 'Ivo', 75.25, 'refunded', 'DE', '2024-03-09'),
    (10, 'Jun', NULL, 'pending', 'US', '2024-03-10');

Practice challenge

For orders that have an amount, return order_id, amount, and size_band: 'small' when amount is below 50, 'medium' when it is below 200, and 'large' otherwise. Order by order_id.

Hint: CASE WHEN amount < 50 THEN 'small' WHEN amount < 200 THEN 'medium' ELSE 'large' END AS size_band, plus WHERE amount IS NOT NULL.

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in CASE WHEN Expressions

Add conditional logic to queries with CASE WHEN: label rows, bucket numbers, map codes to readable values, and count or sum only the rows that match.

  1. 01 · CASE WHEN Basics
  2. 02 · ELSE, NULL, and Branch Order
  3. 03 · Simple CASE for Value Mapping
  4. 04 · Conditional Aggregation

Related guides