SQL chapters

Chapter 7 of 17

CASE expressions

Try this in our SQLite Compiler →

The idea

CASE calculates a value for each row. It does not branch between arbitrary blocks of SQL commands. Put the most specific matching condition first, because the first matching branch supplies the value. ELSE provides a fallback including values not covered by earlier branches.

Worked example

WITH scores(name, score) AS (VALUES ('Asha', 82), ('Ravi', 60))
SELECT name, CASE WHEN score >= 70 THEN 'Pass' ELSE 'Retry' END AS outcome FROM scores ORDER BY name;

What to check

Asha receives Pass and Ravi receives Retry. The query does not issue certificates or modify stored scores.

Practice task

Add a score of exactly 70 and a missing score. Write an explicit branch for missing results before the pass check.

Check your understanding

Explain the result in your own words before changing the example. Change one thing at a time, compare the result with your prediction, and keep the version that demonstrates the concept clearly.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on