🔍
👶 Kids📝 Blog About Contact 🚀 Get Started Free

SQL – CASE

Write conditional logic directly inside SQL queries using the CASE expression — SQL's version of if-then-else.

CASE is SQL’s built-in conditional expression — it works like an if-else chain inside any SELECT, WHERE, or ORDER BY clause. You can use it to create new computed columns, assign category labels, transform values, or even sort rows by custom logic not directly stored in any column.

There are two forms: searched CASE (which evaluates any boolean condition) and simple CASE (which compares one value to a list). Both output a single value based on whichever condition matches first.

Two CASE forms

-- Searched CASE (most flexible)
CASE
  WHEN score >= 90 THEN 'Outstanding'
  WHEN score >= 75 THEN 'Good'
  ELSE 'Needs Work'
END

-- Simple CASE
CASE grade
  WHEN 'A' THEN 'Excellent'
  WHEN 'B' THEN 'Good'
  ELSE 'Other'
END

Try It Yourself — Interactive SQL Editor

Edit the query below and click Run Query ▶ to see live results powered by SQLite running directly in your browser.

SQLite – edit & run
Results
← Click Run Query ▶ to see results

Key Points

  • CASE can appear in SELECT, WHERE, ORDER BY, and HAVING
  • Conditions are evaluated top-to-bottom — first match wins
  • ELSE catches anything not matched by the WHEN clauses
  • Omitting ELSE returns NULL for unmatched rows

Pro Tip from CodesCompiler: The best way to learn SQL is to break things intentionally — modify the query above, change the WHERE conditions, try different columns. Every error teaches you something the docs cannot.

In the next lesson, we continue exploring SQL’s powerful feature set to build your database mastery.