LearnSQLSQL CASE
LOGIC

SQL CASE

Create readable categories from business rules inside a query.

After this lessonTurn thresholds and conditions into status labels.

How it works

CASE adds conditional logic to a SELECT statement. It is ideal for turning raw numeric or coded data into labels that people can understand immediately.

Order your WHEN conditions carefully because the first matching branch is returned. Keep complex business rules documented and test boundary values.

REAL WORK

Classify inventory as REORDER/OK, convert defect rates into severity bands or label late orders.

SYNTAX

The pattern

CASE
  WHEN condition THEN 'Result'
  ELSE 'Other'
END

Example

SELECT ProductName, Stock,
  CASE WHEN Stock < 20 THEN 'REORDER' ELSE 'OK' END AS StockStatus
FROM Products;
TRY IT

Run the example

Edit the query and run it against the built-in demo tables. Nothing is sent to a server.

SQL playground

The learning runner supports SELECT, WHERE, LIKE, IN, BETWEEN, GROUP BY, HAVING, JOIN, aggregates, ORDER BY and LIMIT. Advanced lessons explain additional production SQL concepts even when the mini runner does not execute that syntax.

QUICK CHECK

What does CASE return when no WHEN matches and no ELSE exists?

Progress is stored only in this browser. No account required.