Memra

Conditional logic with CASE

◈ 2 cards

SQL's if/else — bucket and relabel values inline.

if/else, inline

CASE is SQL's conditional expression. It checks conditions top to bottom and returns the first match's value:

SELECT title, price,
       CASE WHEN price < 12 THEN 'budget'
            WHEN price < 20 THEN 'standard'
            ELSE 'premium' END AS band
FROM books;

It works anywhere an expression is allowed — SELECT, WHERE, ORDER BY, even inside an aggregate. There's also a short "simple" form: CASE status WHEN 'paid' THEN 1 ELSE 0 END.

price < 12price < 20ELSECASE'budget''standard''premium'
Conditions are tested top to bottom and the first true one wins, so a book at 9.99 is labelled budget and never reaches the price < 20 branch. ELSE catches whatever is left.
titlepricebandNorthern Light9.99budgetThe Glass Forest14.99standardThe Long Count28.00premiumOne new column, computed per row.
CASE is an expression, not a filter: all ten books come back, each carrying one extra computed value.
NORMAL ~/memra/learn/postgresql/case-expressions utf-8 LF