The SQL Case statement is a useful command that allows you to perform conditional logic in SQL queries. It works similarly to if-else statements in programming languages that enables you to return different values based on specified conditions.
SQL Case Syntax
SELECT column_name,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE resultN
END AS new_column_name
FROM table_name;SQL Case Categorizing Patients by Appointment Status Example
This query joins the Patients table and the Appointments table, categorizing patients as “Active,” “Inactive,” or “Unknown” based on the appointment status.
SELECT p.first_name, p.last_name,
CASE
WHEN a.status = 'Scheduled' THEN 'Active Patient'
WHEN a.status = 'Completed' THEN 'Inactive Patient'
ELSE 'Unknown Status'
END AS patient_status
FROM Patients p
JOIN Appointments a ON p.patient_id = a.patient_id;
SQL Case Visual Diagram



