sqlcmd.net validated sql reference
intermediate updating MySQL MariaDB SQL Server PostgreSQL SQLite

Update a Column Based on Conditions With CASE WHEN

Set a column to different values depending on other column values in the same row by using `CASE WHEN` inside a `SET` clause.

Docker-validated Not currently validation-green

Assign a salary tier to every employee based on their pay

Alice (120000) matches the first condition (>= 100000) and is assigned senior. Dave (95000) and Bob (75000) both match the second condition (>= 60000) and become mid. Carol (45000) matches neither and falls through to the ELSE branch, receiving junior. All four rows are updated in one pass without needing four separate UPDATE statements.

Rows loaded before the example query runs.
Setup
CREATE TABLE employees (name VARCHAR(50), salary INT, tier VARCHAR(20));

INSERT INTO
  employees
VALUES
  ('Alice', 120000, NULL),
  ('Bob', 75000, NULL),
  ('Carol', 45000, NULL),
  ('Dave', 95000, NULL);
Shared across supported engines.
SQL
UPDATE employees
SET
  tier = CASE
    WHEN salary >= 100000 THEN 'senior'
    WHEN salary >= 60000 THEN 'mid'
    ELSE 'junior'
  END;

SELECT
  name,
  salary,
  tier
FROM
  employees
ORDER BY
  salary DESC;
Returned rows for the shared example.
namesalarytier
Alice120000senior
Dave95000mid
Bob75000mid
Carol45000junior

The CASE WHEN syntax inside SET is identical across all supported engines.

Where this command helps.

  • classifying employees into salary tiers based on their pay in a single pass
  • re-coding a status column from numeric codes to descriptive labels

What the command is doing.

A CASE WHEN expression inside a SET clause lets a single UPDATE statement assign different values to rows that meet different conditions, replacing multiple separate updates. The expression evaluates each condition in order and uses the first matching THEN value; rows that match no condition fall through to the ELSE branch (or receive NULL if ELSE is omitted). This pattern is useful for categorising, re-coding statuses, and any situation where the new value depends on the existing data.