Reading history

SQL CASE Expression (CASE WHEN THEN ELSE END)

4 min read 0 views

Learn the SQL CASE expression: searched and simple forms, ELSE and NULL, conditional counting with SUM(CASE ...), pivot-style summaries and custom sort orders.

The CASE expression brings if/else logic into SQL. It lets a query turn numbers into labels, choose different calculations for different rows, and count several categories at once. Because it is an expression, you can use it anywhere a value is allowed: in SELECT, WHERE, ORDER BY and inside aggregate functions.

In this lesson you will learn

  • The searched CASE WHEN ... THEN ... END form
  • The simple CASE column WHEN value form
  • How ELSE and NULL work in CASE
  • Conditional counting and pivot-style summaries
  • Using CASE for custom sort orders

Searched CASE: Labels From Conditions

SELECT name, cgpa,
       CASE
           WHEN cgpa >= 3.75 THEN 'First class'
           WHEN cgpa >= 3.25 THEN 'Second class'
           WHEN cgpa IS NULL THEN 'Not graded'
           ELSE 'Pass'
       END AS result
FROM students
ORDER BY cgpa DESC;

Output

+--------+------+--------------+
| name   | cgpa | result       |
+--------+------+--------------+
| Tania  | 3.95 | First class  |
| Nusrat | 3.82 | First class  |
| Mitu   | 3.67 | Second class |
| Sabbir | 3.55 | Second class |
| Arif   | 3.41 | Second class |
| Imran  | 3.1  | Pass         |
| Rafi   | 2.98 | Pass         |
| Nadia  | NULL | Not graded   |
+--------+------+--------------+
(8 rows)
  • Each WHEN holds a full condition. The conditions are checked from top to bottom, and the first true one decides the result, so put the most specific conditions first.
  • ELSE catches everything else. Without it, unmatched rows get NULL.
  • The NULL CGPA is not caught by the comparisons (they are unknown, not true), so it falls to WHEN cgpa IS NULL. See NULL values for why.
  • Always finish with END, and give the result a name with AS.

Simple CASE and Conditional Aggregation

-- Simple CASE: compare one column with fixed values
SELECT id, customer,
       CASE status
           WHEN 'delivered' THEN 'Done'
           WHEN 'pending'   THEN 'In progress'
           ELSE 'Stopped'
       END AS status_text
FROM orders
WHERE id <= 4;

-- CASE inside aggregates: a pivot-style summary in one row
SELECT SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
       SUM(CASE WHEN status = 'pending'   THEN 1 ELSE 0 END) AS pending,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled,
       SUM(CASE WHEN status = 'delivered' THEN amount END) AS delivered_value
FROM orders;

Output

+----+----------+-------------+
| id | customer | status_text |
+----+----------+-------------+
| 1  | Karim    | Done        |
| 2  | Rina     | Done        |
| 3  | Karim    | Stopped     |
| 4  | Joya     | Done        |
+----+----------+-------------+
(4 rows)

+-----------+---------+-----------+-----------------+
| delivered | pending | cancelled | delivered_value |
+-----------+---------+-----------+-----------------+
| 5         | 2       | 1         | 5750            |
+-----------+---------+-----------+-----------------+
(1 row)
  • The simple form, CASE status WHEN 'delivered' THEN ..., compares one expression with a list of values. It is shorter when every test is an equality.
  • SUM(CASE WHEN condition THEN 1 ELSE 0 END) counts the rows that meet a condition. Several of these in one query produce a pivot-style summary: one row with a column per category.
  • In SUM(CASE WHEN status = 'delivered' THEN amount END), non-matching rows give NULL, which SUM ignores, so only delivered amounts are added: 5750 taka.

CASE in ORDER BY and WHERE

-- Custom order: pending first, then delivered, then cancelled
SELECT id, status
FROM orders
ORDER BY CASE status
             WHEN 'pending' THEN 1
             WHEN 'delivered' THEN 2
             ELSE 3
         END, id;

This sorts by a priority you define instead of alphabetically. CASE can also appear in WHERE, but a plain condition with AND/OR is usually clearer there.

Common Mistakes

  1. Forgetting END, which causes a syntax error.
  2. Putting a broad condition first, so later, more specific branches never run.
  3. Mixing result types, such as text in one branch and numbers in another, which some databases reject.
  4. Using the simple form to test for NULL: CASE cgpa WHEN NULL never matches. Use WHEN cgpa IS NULL in the searched form.

Practice Exercises

Exercise 1. Label each course as “Heavy” (4 or more credits) or “Standard”.

Show answer
SELECT title,
       CASE WHEN credits >= 4 THEN 'Heavy' ELSE 'Standard' END AS load
FROM courses;

Exercise 2. Count students per department split into “Dhaka” and “Outside Dhaka” columns.

Show answer
SELECT dept,
       SUM(CASE WHEN city = 'Dhaka' THEN 1 ELSE 0 END) AS dhaka,
       SUM(CASE WHEN city <> 'Dhaka' THEN 1 ELSE 0 END) AS outside_dhaka
FROM students
GROUP BY dept;

Frequently Asked Questions

Is CASE a statement or an expression?

In standard SQL queries it is an expression that returns a value. Stored-procedure languages also have a CASE statement for control flow, which is a different feature.

What is the difference between CASE and IF()?

IF(condition, a, b) is a MySQL shortcut for a two-way choice. CASE is standard SQL, works in every database and handles any number of branches.

Summary

  • CASE WHEN ... THEN ... ELSE ... END returns the first matching result.
  • The simple form compares one value against a list.
  • SUM(CASE ...) counts or totals categories in one pass.
  • CASE works in SELECT, WHERE, ORDER BY and aggregates.

Next: SQL String Functions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *