SQL / MySQL Intermediate Queries · 8 min read

CASE Expressions in SELECT

Lesson 17 of 33 in the SQL / MySQL learning path.

How do I turn a status code into a label in SQL?

A status code such as confirmed is compact in the table and terse on a report. A CASE expression in the SELECT list maps that code to a label while each enrollment stays its own row. A simple CASE compares one expression with WHEN values. A searched CASE tests a condition, which is the form that belongs inside SUM when a report counts each status.

This lesson uses the school database on MySQL 8. The tables are users, lessons, and enrollments. The queries read enrollments.status and return Enrolled, Waiting, or Cancelled. WHERE still decides which rows survive. CASE only computes a value for the rows that remain.

Syntax & Parameters

Syntax
CASE status
  WHEN 'confirmed' THEN 'Enrolled'
  WHEN 'waitlist' THEN 'Waiting'
  WHEN 'cancelled' THEN 'Cancelled'
  ELSE 'Unknown'
END

Example

queries.sql
CREATE DATABASE IF NOT EXISTS school
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE school;

SET NAMES utf8mb4;

DROP VIEW IF EXISTS roster;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS lessons;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(254) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE lessons (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  title VARCHAR(160) NOT NULL,
  track VARCHAR(80) NOT NULL,
  published_at DATETIME NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE enrollments (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  lesson_id INT UNSIGNED NOT NULL,
  user_id INT UNSIGNED NOT NULL,
  status VARCHAR(20) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_enrollments_lesson_user (lesson_id, user_id),
  CONSTRAINT fk_enrollments_lesson FOREIGN KEY (lesson_id) REFERENCES lessons (id),
  CONSTRAINT fk_enrollments_user FOREIGN KEY (user_id) REFERENCES users (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO users (name, email, created_at) VALUES
  ('Ada Lovelace', 'ada@school.test', '2026-03-01 09:00:00'),
  ('Grace Hopper', 'grace@school.test', '2026-03-14 11:00:00'),
  ('Alan Turing', 'alan@school.test', '2026-03-18 08:30:00');

INSERT INTO lessons (title, track, published_at) VALUES
  ('Algebra I', 'math', '2026-03-02 09:00:00'),
  ('SQL Basics', 'data', '2026-03-10 09:00:00'),
  ('Studio Draft', 'art', NULL);

INSERT INTO enrollments (lesson_id, user_id, status) VALUES
  (1, 1, 'confirmed'),
  (1, 2, 'waitlist'),
  (1, 3, 'cancelled'),
  (2, 1, 'confirmed');

SELECT
  id,
  lesson_id,
  user_id,
  status,
  CASE status
    WHEN 'confirmed' THEN 'Enrolled'
    WHEN 'waitlist' THEN 'Waiting'
    WHEN 'cancelled' THEN 'Cancelled'
    ELSE 'Unknown'
  END AS status_label
FROM enrollments
ORDER BY id;

SELECT
  id,
  lesson_id,
  user_id,
  status,
  CASE status
    WHEN 'confirmed' THEN 'Enrolled'
    WHEN 'waitlist' THEN 'Waiting'
    WHEN 'cancelled' THEN 'Cancelled'
    ELSE 'Unknown'
  END AS status_label
FROM enrollments
WHERE status <> 'cancelled'
ORDER BY id;

SELECT
  lesson_id,
  SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) AS confirmed_count,
  SUM(CASE WHEN status = 'waitlist' THEN 1 ELSE 0 END) AS waitlist_count,
  SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled_count
FROM enrollments
GROUP BY lesson_id
ORDER BY lesson_id;

Expected Output

id | lesson_id | user_id | status    | status_label
1  | 1         | 1       | confirmed | Enrolled
2  | 1         | 2       | waitlist  | Waiting
3  | 1         | 3       | cancelled | Cancelled
4  | 2         | 1       | confirmed | Enrolled
4 rows in set

id | lesson_id | user_id | status    | status_label
1  | 1         | 1       | confirmed | Enrolled
2  | 1         | 2       | waitlist  | Waiting
4  | 2         | 1       | confirmed | Enrolled
3 rows in set

lesson_id | confirmed_count | waitlist_count | cancelled_count
1         | 1               | 1              | 1
2         | 1               | 0              | 0
2 rows in set

Line-by-Line Walkthrough

  1. The script creates school on MySQL 8 and rebuilds users, lessons, and enrollments so the status codes are known.
  2. The first SELECT lists every enrollment and adds status_label with a simple CASE that matches the status column.
  3. confirmed becomes Enrolled, waitlist becomes Waiting, and cancelled becomes Cancelled.
  4. ELSE Unknown runs only when the stored code matches none of the WHEN arms, so a new code is still visible.
  5. CASE does not drop rows. The second SELECT adds WHERE status <> 'cancelled' when the report should hide those seats.
  6. The third SELECT returns one row per lesson_id and uses a searched CASE inside SUM to count each status.
  7. A searched CASE tests a condition in each WHEN. That is the form to use for ranges and for the 1 or 0 inside SUM.
  8. Studio Draft has no enrollment rows, so the grouped query does not invent a zero count for it.
  9. Keep the label mapping in the SQL when a report or a later view must return the words. Send any filter value from PHP as a bound parameter.

Common Pitfalls & Security

CASE labels a code that is already stored. It does not stop an INSERT from saving a status the report has never heard of, and a missing ELSE can turn that code into NULL so the report looks blank.

  • Omit ELSE and an unmapped code returns NULL. The row is still there, but the label column looks empty.
  • A trailing space or a different letter case makes every WHEN miss. Store a short canonical code and match that exact text.
  • SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) counts rows. It does not print the words Enrolled, and lessons with no enrollments never appear.
  • Copying the CASE into every report by hand lets the words drift. One view, taught next to the join lessons, can hold the mapping.
  • CASE is not access control. A cancelled row stays readable until WHERE or a privilege removes it.

Best Practices & Modern Standards

Store the short code in enrollments.status and map it to words at read time. A simple CASE is enough when every arm compares the same column. Use a searched CASE when the test is a range or a boolean you want to add up. Pair the report with a CHECK constraint, or a small lookup table, when the set of codes itself must be enforced.

Pass filter values from application code as bound parameters. Leave the CASE text in the statement, because it is part of the query rather than a data value. When several screens need the same words, put that SELECT in a view so the labels stay in one place.

Real-World Use

The registrar exports a class list for Algebra I. The enrollment table stores confirmed, waitlist, and cancelled. The export query uses CASE so the file the office opens says Enrolled, Waiting, and Cancelled, and a second query counts how many seats are in each group without a second pass in PHP.

Frequently Asked Questions

Does CASE filter rows the way WHERE does?

No. CASE returns a value for each row that WHERE already kept. Add a WHERE clause when cancelled rows should disappear from the list.

What does the query return for a status I forgot to map?

ELSE supplies that value. In this lesson the label is Unknown. Without ELSE, MySQL returns NULL for the label and still returns the row.

How do I count each status in the same query?

Put a searched CASE inside SUM and group by lesson_id. Each matching row adds 1 and every other row adds 0, so the sums are the counts.

When do I use a searched CASE instead of a simple CASE?

Use a simple CASE when one expression is compared with several values. Use a searched CASE when each arm is its own condition, such as status = 'confirmed' or a range test.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…