sqlcmd.net validated sql reference
intermediate conditional-logic MySQL MariaDB SQL Server PostgreSQL SQLite

Return Different Values With CASE WHEN

Evaluate conditions row-by-row inside a `SELECT` to produce computed columns based on branching logic.

Docker-validated Not currently validation-green

Label order totals as low, medium, or high

Conditions are evaluated in order. Order 1 (30) hits the first branch, order 2 (75) hits the second, and order 3 (300) falls through to ELSE.

Rows loaded before the example query runs.
Setup
CREATE TABLE orders (id INT, total INT);

INSERT INTO
  orders (id, total)
VALUES
  (1, 30),
  (2, 75),
  (3, 300);
Shared across supported engines.
SQL
SELECT
  id,
  total,
  CASE
    WHEN total < 50 THEN 'low'
    WHEN total < 200 THEN 'medium'
    ELSE 'high'
  END AS size
FROM
  orders
ORDER BY
  id;
Returned rows for the shared example.
idtotalsize
130low
275medium
3300high

Output is identical across all engines.

Where this command helps.

  • bucketing values into labels or ranges
  • adding derived status text directly in a query result

What the command is doing.

CASE WHEN is SQL's conditional expression. Each row is tested against the WHEN conditions in order, and the first matching branch determines the output value. A trailing ELSE catches any rows that do not match any branch. The expression can appear anywhere a value is expected: SELECT, ORDER BY, WHERE, and GROUP BY.