DELAPARRA
Index
Color
NL
Category: SQL

CASE

Explained by Updated

What is CASE?

CASE: SQL’s if/else expression — return different values per row based on conditions. Handy for bucketing and pivoting. CASE is SQL's if-else expression. It returns a different value per row depending on conditions, such as CASE WHEN total > 1000 THEN 'large' ELSE 'small' END. It is useful for grouping values into buckets, translating codes into readable labels, or counting several categories in one query. SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) counts paid orders while you also count other statuses in the same result.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about CASE

What should you keep in mind with CASE?

Conditions are checked from top to bottom, and the first match wins, so put the most specific ones first. Without an ELSE, unmatched rows get NULL, which can surprise you later. If the same CASE logic appears in many queries, consider storing the result in a column or a lookup table, so the rule lives in one place.

What does an example of CASE look like?

SELECT name, CASE WHEN age < 18 THEN 'minor' WHEN age < 65 THEN 'adult' ELSE 'senior' END AS bracket FROM people;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with C

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.