DataBolt

All Lessons

Introduction to SQL
SQL Lesson 1: Your Sample Database
SQL Lesson 2: SELECT — Reading data
SQL Lesson 3: WHERE — Filtering rows
SQL Lesson 4: AND, OR, NOT
SQL Lesson 5: BETWEEN, IN, LIKE
SQL Lesson 6: NULL — The Mystery Value
SQL Lesson 7: ORDER BY
SQL Lesson 8: LIMIT & OFFSET
SQL Lesson 9: Aggregate Functions
SQL Lesson 10: GROUP BY
SQL Lesson 11: HAVING
SQL Lesson 12: INNER JOINs
SQL Lesson 13: LEFT JOINs
SQL Lesson 14: RIGHT JOINs
SQL Lesson 15: SELF JOINs
SQL Lesson 16: UNION JOINs
SQL Lesson 17: Joining Multiple Tables
SQL Lesson 18: Subqueries
SQL Lesson 19: CTEs (WITH)
SQL Lesson 20: CASE Statements
SQL Lesson 21: Window Functions
SQL Lesson 22: String Functions
SQL Lesson 23: Date & Time Functions
SQL Lesson 24: INSERT, UPDATE, DELETE
SQL Lesson 25: CREATE TABLE & DDL
SQL Lesson 26: Indexes & Performance
SQL Lesson 27: Transactions & ACID
SQL Lesson 28: SQL Execution Order
SQL Lesson 29: 50 Practice Problems

CHAPTER 21

CASE Statements

If-else logic that lives inside your SQL.

IN THIS CHAPTER

  • CASE WHEN ... THEN ... END syntax
  • Using CASE to label and categorise rows
  • CASE inside aggregate functions — the pivot pattern

17.1 - Basic Case

Label employees by salary band

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)

Count by band in one row

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 👇

Exercise:

Tasks

1.👉Classify employees as 'High' or 'Low' based on salary greater than 70000.
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.
Stuck? Read this task's