Menu
CoddyTech

Labels with CASE

Part of the First Queries section of Coddy's PostgreSQL journey. Lesson 13 of 20.

CASE creates a value by checking conditions in order. WHEN introduces a condition, THEN supplies its value, and ELSE supplies the fallback. END closes the expression.

Input table products:

idnamecategorypricestockactivenote
1Maptravel125TrueNULL
2Notebookbooks80TrueRecycled
3Atlasbooks243FalseNULL
4Mughome128TrueBlue
5lamphome302FalseClearance
6Mini maptravel610TrueNULL
SELECT id, CASE WHEN price >= 20 THEN 'premium' ELSE 'standard' END AS tier FROM products ORDER BY id;

Ids 3 and 5 receive premium; the remaining rows receive standard. CASE changes an output value rather than filtering rows. With several WHEN branches, the first true condition wins.

Use CASE WHEN condition THEN value ELSE fallback END to label each row.

challenge icon

Challenge

Easy

Return id and availability: use sold_out when stock is zero, low when stock is below 4, and ready otherwise. Order by id.

The input tables are shown in the test panel. Each run starts from fresh data. Return the named columns in the stated order; do not hard-code the displayed rows.

Try it yourself

-- Write your SQL here.
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in First Queries

Practice on your own: PostgreSQL playground