Lesson 42 +10 XP

CASE Expression

The CASE expression is like an if-then-else in SQL. It checks conditions and returns a value for the first one that is true.

Basic example


sql

### SELECT OrderID, Quantity,

### CASE

### WHEN Quantity > 30 THEN 'big'

### WHEN Quantity > 20 THEN 'medium'

### ELSE 'small'

### END AS Size

### FROM OrderDetails;

How it works

  1. Conditions are checked top to bottom.
  1. The first TRUE condition wins.
  1. If none match, ELSE is returned.
  1. END finishes the CASE; AS Size names the column.

ELSE is optional

If there is no ELSE and nothing matches, the result is NULL.

CASE in WHERE


sql

### SELECT CustomerName, City

### FROM Customers

### ORDER BY
(CASE

### WHEN City IS NULL THEN 1

### ELSE 0

### END), City;

Sorts NULL cities last.

CASE in ORDER BY

CASE is also handy for custom sorting, like always keeping a certain product on top.

TL;DR

  • CASE is if-then-else for SQL.
  • First true WHEN wins.
  • ELSE is the fallback (NULL if missing).
  • Usable in SELECT, WHERE, and ORDER BY.