Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Advanced SQL Reporting: CASE & Conditional Aggregation

Recommended resources

Welcome to your next lesson in our SQL for Data Science course. Last time, we explored how to create sophisticated trend analyses using window frames to calculate running totals and moving averages. You learned to define a specific ROWS or RANGE of data for your window functions to operate on, giving you fine-grained control over sequential calculations.

Today, we'll introduce another fundamental tool for advanced analysis: the CASE statement. This is SQL's way of handling conditional logic, similar to an if/else statement in a programming language. You will learn how to use CASE to create new categories from your data. More importantly, you'll discover how to combine it with aggregate functions like SUM() and COUNT() to perform conditional aggregation. This technique is the key to creating custom summary reports and pivoting data—transforming it from a "long" to a "wide" format—all within a single, efficient query.

1. The CASE Statement: SQL's Conditional Logic

At its core, the CASE statement allows you to apply if/then/else logic directly within your SELECT clause. It evaluates a series of conditions and returns a specific value as soon as a condition is met.

The basic structure is:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ...
    ELSE else_result
END

This is extremely useful for segmenting data into custom groups. For example, you could categorize customers into 'New', 'Regular', or 'VIP' based on their purchase history, or label products as 'High-Margin' or 'Low-Margin'.

To get a clear visual understanding of how the CASE statement works, please watch the following video.

SQL CASE WHEN Statement (Visually Explained) | #SQL Course 20

This video from the "Data with Baraa" channel provides a fantastic visual breakdown of the CASE statement's syntax and execution flow.

Watch the first part, from the beginning to the end of the demo, to understand the keywords (CASE, WHEN, THEN, ELSE, END) and how SQL processes conditions sequentially. Then, continue watching the next segment, which demonstrates the most common use case: categorizing data. Pay attention to how a new categorical column is created and then used for aggregation in a subquery.

As the video showed, the CASE statement is evaluated for each row, and the order of the WHEN clauses matters. SQL will stop at the first WHEN clause that evaluates to true. The optional ELSE clause acts as a default, catching any rows that don't meet any of the preceding conditions. If ELSE is omitted and no conditions are met, the result will be NULL.

For a quick written reference on the syntax, this article is a great resource.

SQL CASE Statement | Intermediate SQL

This article from ThoughtSpot provides a concise summary of the CASE statement.

Read the sections "The SQL CASE statement" and "Adding multiple conditions to a CASE statement". Focus on the syntax for simple and multi-condition CASE expressions.


2. Conditional Aggregation: Unleashing the Power of CASE

While creating categories is useful, the CASE statement truly shines when you place it inside an aggregate function like SUM(), COUNT(), or AVG(). This is called conditional aggregation.

This technique allows you to aggregate different subsets of your data in parallel, within a single GROUP BY query. Instead of writing multiple queries with different WHERE clauses and joining them, you can compute multiple metrics in one pass.

The most common pattern looks like this:

SUM(CASE WHEN condition THEN column_to_sum ELSE 0 END)

Let's break it down:

  • The CASE statement checks the condition for each row.
  • If the condition is true, it returns the value from column_to_sum.
  • If the condition is false, it returns 0.
  • The SUM() function then adds up these results. The effect is that you are only summing the values for rows that meet your condition.
This image shows examples of conditional aggregation. The query on the bottom uses `COUNT(CASE WHEN ...)` to count orders placed on a specific date, grouped by `CustomerId`. This is a classic example of creating a custom report with conditional logic.

Let's see how to apply this to create targeted reports.

SQL CASE WHEN Statement (Visually Explained) | #SQL Course 20

Let's return to the "Data with Baraa" video to see a practical example of conditional aggregation.

Watch the section from conditional aggregations. The instructor demonstrates a common pattern: creating a "flag" (1 or 0) with a CASE statement and then summing the flag to get a conditional count.

This method of "flagging" rows with a 1 or 0 inside a CASE statement is fundamental for analytics. By summing the flags, you get a conditional COUNT. By summing a value (like revenue) conditionally, you get a conditional SUM.

The following article explains why this is such an important pattern in data science and analytics interviews.

SQL Conditional SUM: SUM(CASE WHEN) Syntax, ...

This guide from InterviewQuery frames conditional aggregation as a core skill for data analysts.

Read the Introduction and the section on "What Is SUM(CASE WHEN) in SQL?" to solidify your understanding of the core concept and syntax. Review "Why Use Conditional Sums?" to see the benefits, such as improved performance and query readability. Finally, look at the "Examples of SUM (CASE WHEN) in Practice," focusing on the "Counting Event Types Per User" and "Pivot-Style Aggregation" examples. These show how to build compact, insightful reports.


3. Pivoting Data: From Rows to Columns

One of the most powerful applications of conditional aggregation is pivoting data. This means transforming data from a "long" format (where attributes are stored in rows) to a "wide" format (where attributes are stored in columns). This is incredibly useful for creating summary dashboards and reports that are easy to read.

Imagine you have a table of sales data like this:

region category sales
'North' 'Electronics' 1000
'North' 'Clothing' 500
'South' 'Electronics' 800
'South' 'Clothing' 900

You want to create a report with one row per region and separate columns for Electronics sales and Clothing sales.

Desired Output:

region electronics_sales clothing_sales
'North' 1000 500
'South' 800 900

You can achieve this with conditional aggregation:

SELECT
  region,
  SUM(CASE WHEN category = 'Electronics' THEN sales ELSE 0 END) AS electronics_sales,
  SUM(CASE WHEN category = 'Clothing' THEN sales ELSE 0 END) AS clothing_sales
FROM sales_data
GROUP BY region;

This video provides a clear, step-by-step walkthrough of this exact process.

SQL Convert Rows to Columns and Columns to Rows without using Pivot Functions

This video from Ankit Bansal demonstrates how to pivot data without using the official PIVOT function, which is a more universal and flexible approach.

Watch from the query implementation. The instructor builds the query step-by-step, first creating the CASE statements to isolate the values for each new column, and then wrapping them in a SUM() and GROUP BY to complete the pivot.

This SUM(CASE WHEN ...) pattern is the standard, cross-database method for pivoting data and is an essential skill for any data professional.


4. Practice Exercises

Let's put these concepts into practice. Consider the following transactions table:

transaction_id customer_id transaction_date product_category amount
1 101 '2023-04-01' 'Groceries' 75.50
2 102 '2023-04-01' 'Electronics' 250.00
3 101 '2023-04-02' 'Clothing' 120.00
4 103 '2023-04-02' 'Groceries' 45.20
5 102 '2023-04-03' 'Clothing' 85.00
6 101 '2023-04-03' 'Electronics' 499.99

Problem 1: Categorize Transaction Sizes

Task: Write a query that returns the transaction_id, amount, and a new column transaction_size. The size should be 'Small' for amounts under 100, 'Medium' for amounts between 100 and 250 (inclusive), and 'Large' for amounts over 250.

Solution
SELECT
  transaction_id,
  amount,
  CASE
    WHEN amount < 100 THEN 'Small'
    WHEN amount >= 100 AND amount <= 250 THEN 'Medium'
    ELSE 'Large'
  END AS transaction_size
FROM transactions;

Problem 2: Create a Customer Spending Report

Task: Write a query that pivots the data to show the total amount each customer spent in each product category. The final report should have one row per customer_id.

Desired Output:

customer_id groceries_total electronics_total clothing_total
101 75.50 499.99 120.00
102 0.00 250.00 85.00
103 45.20 0.00 0.00
Solution
SELECT
  customer_id,
  SUM(CASE WHEN product_category = 'Groceries' THEN amount ELSE 0 END) AS groceries_total,
  SUM(CASE WHEN product_category = 'Electronics' THEN amount ELSE 0 END) AS electronics_total,
  SUM(CASE WHEN product_category = 'Clothing' THEN amount ELSE 0 END) AS clothing_total
FROM transactions
GROUP BY customer_id
ORDER BY customer_id;

Conclusion

In this lesson, you've learned how to harness conditional logic in SQL using the CASE statement. While useful for basic categorization, its true power is unlocked through conditional aggregation, allowing you to build complex, pivoted reports efficiently.

Key Takeaways:

  • The CASE statement provides if/then/else functionality directly in your queries.
  • You can use CASE to create new columns with categorical or derived values.
  • Conditional aggregation is the technique of placing a CASE statement inside an aggregate function (SUM, COUNT, AVG).
  • The SUM(CASE WHEN ...) pattern is the standard way to pivot data, transforming it from a long to a wide format for creating summary reports.

In our next lesson, we will start applying these advanced SQL techniques—including CASE, window functions, and JOINs—to solve realistic business problems. We'll begin by tackling a common data science challenge: performing a user retention analysis.