Academic Block

SQL CASE Get Certified

Learn how the CASE expression brings conditional logic into SQL queries, letting you return different values based on conditions.

What is the CASE Expression?

CASE evaluates a series of conditions and returns the result of the first condition that is true. It can be used in the SELECT list, in ORDER BY, in GROUP BY, inside aggregate functions, and in many other places.

There are two common forms:

  • Searched CASE – CASE WHEN condition THEN result … END
  • Simple CASE – CASE expression WHEN value THEN result … END

Basic Searched CASE

The most flexible form tests any Boolean condition.

What this code does: Classifies each student’s score into “Excellent”, “Pass” or “Needs Improvement”.

WITH students(student_id, student_name, score) AS (
  VALUES
    (1, 'Aarav', 86),
    (2, 'Meera', 72),
    (3, 'Kabir', 94),
    (4, 'Riya', 61)
)
SELECT
  student_name,
  score,
  CASE
    WHEN score >= 80 THEN 'Excellent'
    WHEN score >= 60 THEN 'Pass'
    ELSE 'Needs Improvement'
  END AS performance
FROM students
ORDER BY score DESC;

Multiple WHEN Clauses

You can list as many WHEN clauses as you need. They are evaluated from top to bottom; the first match wins.

What this code does: Puts each product into a price category: Premium, Mid-Range, Budget or Low Cost.

WITH products(product_id, product_name, price) AS (
  VALUES
    (1, 'Wireless Mouse', 900),
    (2, 'Mechanical Keyboard', 2800),
    (3, '4K Monitor', 18500),
    (4, 'USB Cable', 350)
)
SELECT
  product_name,
  price,
  CASE
    WHEN price >= 10000 THEN 'Premium'
    WHEN price >= 2000 THEN 'Mid-Range'
    WHEN price >= 500 THEN 'Budget'
    ELSE 'Low Cost'
  END AS price_category
FROM products
ORDER BY price DESC;

CASE with ELSE

The optional ELSE clause supplies a value when none of the WHEN conditions are true.

What this code does: Maps known departments to friendly labels and uses “Other” for anything else.

WITH employees(employee_id, employee_name, department) AS (
  VALUES
    (1, 'Anaya', 'Engineering'),
    (2, 'Rohan', 'Design'),
    (3, 'Mira', 'Sales'),
    (4, 'Dev', 'Support')
)
SELECT
  employee_name,
  department,
  CASE
    WHEN department = 'Engineering' THEN 'Technical'
    WHEN department = 'Design' THEN 'Creative'
    WHEN department = 'Sales' THEN 'Business'
    ELSE 'Other'
  END AS department_type
FROM employees
ORDER BY employee_id;

CASE Without ELSE

If no condition matches and there is no ELSE, the expression returns NULL.

What this code does: Labels large and medium orders; the two smaller orders receive NULL because they do not match any WHEN clause.

WITH orders(order_id, customer_name, amount) AS (
  VALUES
    (101, 'Neha', 1200),
    (102, 'Arjun', 4500),
    (103, 'Tara', 800),
    (104, 'Vikram', 6200)
)
SELECT
  order_id,
  customer_name,
  amount,
  CASE
    WHEN amount >= 5000 THEN 'Large Order'
    WHEN amount >= 2000 THEN 'Medium Order'
  END AS order_size
FROM orders
ORDER BY amount DESC;

Simple CASE Expression

When you are comparing one expression against a list of possible values, the simple form is more concise.

What this code does: Converts the status codes “completed”, “in_progress” and “pending” into readable labels.

WITH tasks(task_id, task_name, status) AS (
  VALUES
    (1, 'Design Homepage', 'completed'),
    (2, 'Write Documentation', 'pending'),
    (3, 'Test Login Form', 'completed'),
    (4, 'Update Database', 'in_progress')
)
SELECT
  task_name,
  status,
  CASE status
    WHEN 'completed' THEN 'Done'
    WHEN 'in_progress' THEN 'Working'
    WHEN 'pending' THEN 'Waiting'
    ELSE 'Unknown'
  END AS status_label
FROM tasks
ORDER BY task_id;

CASE with Text Values

Simple CASE works equally well with text columns.

What this code does: Turns priority codes into human-readable attention levels.

WITH tickets(ticket_id, subject, priority) AS (
  VALUES
    (1, 'Password Reset', 'high'),
    (2, 'Profile Update', 'low'),
    (3, 'Payment Issue', 'critical'),
    (4, 'Login Problem', 'medium')
)
SELECT
  ticket_id,
  subject,
  priority,
  CASE priority
    WHEN 'critical' THEN 'Immediate Attention'
    WHEN 'high' THEN 'High Attention'
    WHEN 'medium' THEN 'Normal Attention'
    WHEN 'low' THEN 'Low Attention'
    ELSE 'Unclassified'
  END AS priority_label
FROM tickets
ORDER BY ticket_id;

CASE with Calculations

Different calculations can be performed depending on a condition.

What this code does: Applies a 10 % discount to amounts ≥ 10 000, a 5 % discount to amounts ≥ 3 000, and leaves smaller amounts unchanged.

WITH sales(sale_id, product, amount) AS (
  VALUES
    (1, 'Laptop Bag', 3200),
    (2, 'Desk Lamp', 1800),
    (3, 'Office Chair', 12500),
    (4, 'Notebook', 450)
)
SELECT
  product,
  amount,
  CASE
    WHEN amount >= 10000 THEN amount * 0.90
    WHEN amount >= 3000 THEN amount * 0.95
    ELSE amount
  END AS final_amount
FROM sales
ORDER BY amount DESC;

CASE with NULL Handling

Combine CASE with IS NULL to replace missing values with a friendly message.

What this code does: Shows “Phone Not Available” when the phone column is NULL and “Phone Available” otherwise.

WITH customers(customer_id, customer_name, phone) AS (
  VALUES
    (1, 'Isha', '9876543210'),
    (2, 'Karan', NULL),
    (3, 'Simran', '9123456780'),
    (4, 'Aditya', NULL)
)
SELECT
  customer_name,
  CASE
    WHEN phone IS NULL THEN 'Phone Not Available'
    ELSE 'Phone Available'
  END AS phone_status
FROM customers
ORDER BY customer_id;

CASE with AND / OR

Complex Boolean expressions can be used inside WHEN clauses.

What this code does: Classifies applicants using both score and age criteria.

WITH applicants(applicant_id, applicant_name, age, score) AS (
  VALUES
    (1, 'Aarav', 24, 88),
    (2, 'Meera', 31, 76),
    (3, 'Kabir', 27, 92),
    (4, 'Riya', 22, 68)
)
SELECT
  applicant_name,
  age,
  score,
  CASE
    WHEN score >= 85 AND age <= 30 THEN 'Strong Candidate'
    WHEN score >= 75 OR age <= 25 THEN 'Potential Candidate'
    ELSE 'Needs Review'
  END AS evaluation
FROM applicants
ORDER BY score DESC;

CASE in ORDER BY (Custom Sort Order)

CASE is frequently used to define a custom sort order that is not alphabetical or numeric.

What this code does: Sorts support tickets so that critical tickets appear first, then high, medium and low.

WITH support_tickets(ticket_id, subject, priority) AS (
  VALUES
    (101, 'Email Problem', 'low'),
    (102, 'Payment Failed', 'critical'),
    (103, 'Login Error', 'high'),
    (104, 'Profile Update', 'medium')
)
SELECT
  ticket_id,
  subject,
  priority
FROM support_tickets
ORDER BY
  CASE priority
    WHEN 'critical' THEN 1
    WHEN 'high' THEN 2
    WHEN 'medium' THEN 3
    WHEN 'low' THEN 4
    ELSE 5
  END;

CASE with Aggregate Functions

A classic pattern is to use CASE inside SUM or COUNT for conditional aggregation.

What this code does: Counts the total number of orders, the number of large orders (≥ 5000) and the number of regular orders.

WITH orders(order_id, customer, amount) AS (
  VALUES
    (1, 'Aman', 1200),
    (2, 'Neha', 6500),
    (3, 'Ravi', 2800),
    (4, 'Tanya', 9100),
    (5, 'Vikram', 1500)
)
SELECT
  COUNT(*) AS total_orders,
  SUM(CASE WHEN amount >= 5000 THEN 1 ELSE 0 END) AS large_orders,
  SUM(CASE WHEN amount < 5000 THEN 1 ELSE 0 END) AS regular_orders
FROM orders;

CASE with GROUP BY

You can group by a CASE expression to produce summary rows for each category you define.

What this code does: Groups transactions into Large / Medium / Small buckets and shows the count and total amount for each bucket.

WITH transactions(transaction_id, amount) AS (
  VALUES
    (1, 450),
    (2, 1200),
    (3, 3500),
    (4, 7800),
    (5, 920)
)
SELECT
  CASE
    WHEN amount >= 5000 THEN 'Large'
    WHEN amount >= 1000 THEN 'Medium'
    ELSE 'Small'
  END AS transaction_size,
  COUNT(*) AS transaction_count,
  SUM(amount) AS total_amount
FROM transactions
GROUP BY
  CASE
    WHEN amount >= 5000 THEN 'Large'
    WHEN amount >= 1000 THEN 'Medium'
    ELSE 'Small'
  END
ORDER BY total_amount DESC;

CASE Structure Summary

Keyword
Purpose
WHEN
Defines a condition to test
THEN
Value returned when the preceding WHEN is true
ELSE
Optional fallback value when no WHEN matches
END
Required terminator of the CASE expression

Common Uses of CASE

  • Classify numeric values into readable categories.
  • Convert status or priority codes into friendly labels.
  • Handle NULL values with meaningful substitutes.
  • Perform different calculations based on a condition.
  • Create custom sort orders in ORDER BY.
  • Build conditional counts and sums inside aggregates.
  • Produce grouped report categories.

Best Practices

  • Place the most specific conditions before more general ones.
  • Always consider whether an ELSE clause is needed; otherwise unmatched rows become NULL.
  • Give clear aliases to CASE expressions so the result set is easy to read.
  • Format each WHEN … THEN pair on its own line for readability.
  • Remember that CASE returns the result of the first matching WHEN.

The CASE expression is SQL’s built-in conditional logic. It lets you classify data, replace codes with readable labels, perform different calculations, create custom sort orders and produce conditional aggregates – all inside a single query. Click Test My Code on any example to run it live, or Code Explanation to walk through the query block by block.

Ctrl + Enter to run code in the editor Esc to close the editor

🧪 Test Your SQL Code

Edit the SQL code on the left and click "Run Code" to see the result on the right.

📝 SQL Code
👁️ Preview (query result)

Click "Run Code" to see the result here.