SQL beginner CASE WHEN conditional categorize pivot

SQL CASE WHEN: Conditional Logic in Queries

CASE WHEN Statement is a SQL query that case evaluates conditions top to bottom. Formula Genius generates and validates this formula automatically from a plain-English prompt.

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

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 any formula in plain English and Formula Genius will generate, explain, and validate it — instantly.