Chapter 13 · Lesson 2 of 4

ELSE, NULL, and Branch Order

Learn why CASE stops at the first matching branch, what happens without ELSE, and why NULL values need an IS NULL check before any comparison.

CASE checks its branches from top to bottom and stops at the first one that is true. Order your conditions from most specific to most general.

If no branch matches and there is no ELSE, the result is NULL:

SELECT order_id, CASE WHEN amount > 300 THEN 'big' END AS flag
FROM shop_orders

Missing values are the classic surprise. A comparison with NULL, such as NULL < 100, is neither true nor false, so it never matches a WHEN. The row falls through to ELSE and gets a label it does not deserve.

Handle missing values explicitly with a first branch that uses IS NULL:

SELECT
  order_id,
  CASE
    WHEN amount IS NULL THEN 'missing'
    WHEN amount < 100 THEN 'under 100'
    ELSE '100 or more'
  END AS amount_label
FROM shop_orders

Without that first branch, Jun's order (amount NULL) would be labelled '100 or more'.

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 all 10 orders, return order_id and amount_label: 'missing' when amount is NULL, 'under 100' when amount is below 100, and '100 or more' otherwise. Order by order_id.

Hint: Put WHEN amount IS NULL THEN 'missing' first, before the comparison branches.

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