Back to SQL Notes
Topic #92

SQL CASE Statement

CASE adds if/else-style logic directly inside a query — evaluating conditions and returning different values based on which one matches.

Syntax

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

Sample Table: employees

namesalary
Aman65000
Riya52000
Neha38000

Example

SELECT name, salary,
    CASE
        WHEN salary >= 60000 THEN 'Senior Band'
        WHEN salary >= 45000 THEN 'Mid Band'
        ELSE 'Entry Band'
    END AS salary_band
FROM employees;

Output:

namesalarysalary_band
Aman65000Senior Band
Riya52000Mid Band
Neha38000Entry Band

WHEN conditions are checked top to bottom — the first one that matches wins, so order them from most specific to least specific.

CASE Inside Aggregates — A Very Common Pattern

SELECT
    SUM(CASE WHEN department = 'Engineering' THEN salary ELSE 0 END) AS engineering_total,
    SUM(CASE WHEN department = 'Marketing' THEN salary ELSE 0 END) AS marketing_total
FROM employees;

This is the standard way to "pivot" data — turning row values into separate summary columns — without a dedicated PIVOT feature.

Simple CASE Form

SELECT name,
    CASE department
        WHEN 'Engineering' THEN 'Tech'
        WHEN 'Marketing' THEN 'Growth'
        ELSE 'Other'
    END AS team_group
FROM employees;

Shorter when every branch is checking the same column for exact equality.

Common Mistakes

  • Forgetting ELSE — without it, non-matching rows return NULL instead of a sensible default, which can silently break downstream logic
  • Ordering WHEN conditions incorrectly — e.g. checking salary >= 45000 before salary >= 60000 means high earners never reach the second condition

Interview Relevance

The "pivot with CASE + SUM" pattern above is asked constantly in data analyst interviews — practice it until it's automatic.

Practice Question

Write a query that labels each order as 'Small' (under 500), 'Medium' (500–2000), or 'Large' (over 2000) based on its total_amount.

Want to go beyond the notes?

Join Coding Now Tech Institute's SQL course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

SQL CASE Statement – FAQs

Quick answers about learning SQL CASE Statement in SQL.

This free note from Coding Now Tech Institute explains SQL CASE Statement in SQL — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every SQL topic on Coding Now Tech Institute, including SQL CASE Statement, is 100% free with no signup required.
With focused practice, most students grasp SQL CASE Statement in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now