We’re improving Formula Genius. We’re redesigning the app and fixing issues along the way. Sorry for any disruption, and thank you for your patience.
SQL beginner

SQL CASE WHEN: Conditional Logic in Queries

CASE WHEN is SQL's IF-THEN-ELSE. Categorize data, create conditional aggregations, and build pivot-like outputs.

Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.

The formula

Prompt

"Categorize orders as Small, Medium, or Large based on amount"

SQL
SELECT order_id, amount,
  CASE
    WHEN amount < 100 THEN 'Small'
    WHEN amount < 1000 THEN 'Medium'
    ELSE 'Large'
  END AS order_size
FROM orders;

CASE evaluates conditions top to bottom. First match wins. An order of $50 hits 'Small', $500 hits 'Medium', $5000 falls through to 'Large'. The result appears as a new column called order_size.

Step-by-step breakdown

  1. CASE opens the conditional block
  2. WHEN amount < 100 THEN 'Small' — first condition checked
  3. WHEN amount < 1000 THEN 'Medium' — only checked if first is false
  4. ELSE 'Large' — catches everything remaining
  5. END AS order_size — closes CASE and names the output column

Edge cases & warnings

  • Without ELSE, non-matching rows return NULL
  • Conditions are evaluated in order — put the most restrictive first
  • CASE works in SELECT, WHERE, ORDER BY, GROUP BY, and HAVING
  • NULL comparisons need IS NULL, not = NULL

Examples

Prompt

"amount = 50"

SQL
Small
Prompt

"amount = 500"

SQL
Medium
Prompt

"amount = 5000"

SQL
Large

Frequently asked questions

Can I use CASE in GROUP BY?

Yes. You can group by the CASE expression or reference the alias in databases that support it. In standard SQL, repeat the CASE in GROUP BY.

How do I do conditional aggregation?

SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) counts active records. This creates pivot-table-like outputs.

Can't find what you need?

Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.