SQL Conditional

SQL CASE WHEN: Conditional Logic in Queries (Complete Guide)

SQL CASE WHEN for if-then-else logic in SELECT, WHERE, ORDER BY, and UPDATE. The most powerful conditional expression in SQL.

Mar 12, 20266 min read

Overview

CASE WHEN is SQL's if-then-else. It works everywhere: SELECT, WHERE, ORDER BY, GROUP BY, UPDATE, and inside aggregate functions.

All Databases

-- Simple CASE:
SELECT name,
  CASE status
    WHEN 'A' THEN 'Active'
    WHEN 'I' THEN 'Inactive'
    WHEN 'P' THEN 'Pending'
    ELSE 'Unknown'
  END AS status_label
FROM users;

-- Searched CASE (with conditions):
SELECT name, salary,
  CASE
    WHEN salary >= 100000 THEN 'Senior'
    WHEN salary >= 50000 THEN 'Mid'
    WHEN salary >= 30000 THEN 'Junior'
    ELSE 'Intern'
  END AS level
FROM employees;

-- CASE in ORDER BY:
SELECT * FROM tasks
ORDER BY
  CASE priority
    WHEN 'critical' THEN 1
    WHEN 'high' THEN 2
    WHEN 'medium' THEN 3
    ELSE 4
  END;

-- CASE in aggregate (conditional counting):
SELECT
  COUNT(CASE WHEN status = 'active' THEN 1 END) AS active,
  COUNT(CASE WHEN status = 'inactive' THEN 1 END) AS inactive,
  SUM(CASE WHEN type = 'credit' THEN amount ELSE -amount END) AS balance
FROM transactions;

-- CASE in UPDATE:
UPDATE products
SET price = CASE
  WHEN category = 'Electronics' THEN price * 1.10
  WHEN category = 'Clothing' THEN price * 1.05
  ELSE price
END;

-- CASE in WHERE:
SELECT * FROM orders
WHERE CASE
  WHEN @show_all = 1 THEN 1
  ELSE CASE WHEN status = 'active' THEN 1 ELSE 0 END
END = 1;

Skip the Syntax Lookup

Instead of memorizing CASE WHEN syntax for each database, describe what you need in plain English and let AI2SQL generate the correct query.

Try AI2SQL Free

No credit card required

Frequently Asked Questions

How do I write if-else logic in SQL?

Use CASE WHEN condition THEN result WHEN condition2 THEN result2 ELSE default END. This works in SELECT, WHERE, ORDER BY, UPDATE, and inside aggregate functions.

Can I use CASE WHEN inside SUM or COUNT?

Yes. SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) counts active rows. This is a common pattern for pivot-like queries.

Can AI2SQL generate CASE WHEN queries?

Yes. Describe conditional logic like 'categorize users by age: under 18 is minor, 18-65 is adult, over 65 is senior' and AI2SQL generates the CASE WHEN.

Generate SQL from Plain English

Stop looking up syntax. Describe what you need and AI2SQL writes the query.

Try AI2SQL Free

No credit card required