SQL CASE Keyword
The CASE keyword in SQL is used to create conditional logic in a query. It allows you to return different values based on specific conditions — similar to an IF-THEN-ELSE statement.
SQL CASE Syntax
SQL
x
1
SELECT column1,
2
CASE
3
WHEN condition1 THEN result1
4
WHEN condition2 THEN result2
5
...
6
ELSE result_default
7
END AS alias_name
8
FROM table_name;
You can also use CASE inside an ORDER BY clause:
SQL
1
1
SELECT column1, column2
2
FROM table_name
3
ORDER BY
4
CASE
5
WHEN condition THEN sort_column1
6
ELSE sort_column2
7
END;
SQL CASE Example with Appointments Table
The following SQL statement shows the appointment ID, status, and a label that changes depending on the value of the status column. This query returns all appointment records and adds a new column status_label based on the value of status.
SQL
1
1
SELECT appointment_id, status,
2
CASE
3
WHEN status = 'Confirmed' THEN 'Confirmed'
4
WHEN status = 'Scheduled' THEN 'Waiting'
5
ELSE 'Unknown Status'
6
END AS status_label
7
FROM Appointments;

SQL CASE Example in ORDER BY Clause (Patients Table)
This example orders the patients by last_name, but if last_name is NULL, it will order by first_name instead. This ensures that even rows with missing last names are properly sorted using first names.
SQL
1
1
SELECT first_name, last_name
2
FROM Patients
3
ORDER BY
4
CASE
5
WHEN last_name IS NULL THEN first_name
6
ELSE last_name
7
END;
