Available Tables

Next →

Using CASE Statements for Conditional Logic

The CASE statement lets you add conditional logic to your SQL queries. It works like an IF-THEN-ELSE statement, allowing you to create new computed columns based on conditions.

Syntax Overview

CASE 
    WHEN condition1 THEN result1    
    WHEN condition2 THEN result2    
    ELSE result_default  
END

You can use CASE inside SELECT, WHERE, ORDER BY, and more.

Example: Categorizing Students by Age

To classify students as 'Minor' or 'Adult' based on their age:

SELECT name, age,
CASE
	WHEN age < 18 THEN 'Minor'
    ELSE 'Adult'
END AS age_group
FROM students;

This adds a new column age_group with the category for each student.

CASE statements make your queries more flexible and powerful for real-world data scenarios.