Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to SQL Notes
Topic #213

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.

Related SQL Notes

Want to go beyond the notes?

Join CodingNow's SQL course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →