DataBolt

SQL LEARNING PLATFORM

19

CHAPTER 19

CASE Statements

If-else logic that lives inside your SQL.

4

Learning Blocks

SQL

Interactive Queries

In This Chapter

Concepts you'll master

1

CASE WHEN ... THEN ... END syntax

2

Using CASE to label and categorise rows

3

CASE inside aggregate functions — the pivot pattern

17.1 - Basic Case

SQL QUERY
SELECT name, salary,
    CASE
        WHEN salary < 60000 THEN 'Junior'
        WHEN salary < 75000 THEN 'Mid-Level'
        ELSE 'Senior'
    END AS band
FROM employees ORDER BY salary;

17.2 - CASE in Aggregates (The Pivot Pattern)

SQL QUERY
SELECT
    SUM(CASE WHEN salary < 60000 THEN 1 ELSE 0 END) AS junior,
    SUM(CASE WHEN salary BETWEEN 60000 AND 74999 THEN 1 ELSE 0 END)
AS mid,
    SUM(CASE WHEN salary >= 75000 THEN 1 ELSE 0 END) AS senior
FROM employees;

Interview Tip: This SUM(CASE WHEN ... END) pattern is the standard way to pivot rows into columns in SQL. It appears in almost every data analyst/data engineer interview. Know it cold.

Exercise

Practice your SQL skills

SQL EDITOR
Press semicolon (;) to auto-run query

Tasks

Complete all SQL challenges

1

Classify employees as 'High' or 'Low' based on salary greater than 70000.

Current Task
2

Classify employees as 'Tech' or 'Non-Tech' based on department.

3

Categorize employees into 'Low', 'Medium', and 'High' salary groups.

4

Show whether an employee has a manager or not.

5

Create a custom category: 'Top IT' for IT employees with salary > 70000, 'HR Team' for HR, and 'Other' for rest.

Need help solving this task?