Beginner

380. CASE with Aggregate Functions

Learn how CASE expressions can be combined with aggregate functions for conditional analysis.

📘 Lesson 380 of 728 ⏱ 12 min 🎯 Intermediate

CASE can be used inside aggregate functions such as SUM and COUNT to calculate values only for rows meeting specific conditions.

Conditional aggregation is one of the most powerful SQL techniques for creating business metrics in a single query.

Calculate total sales for successful transactions.

SQL
SELECT
    SUM(
        CASE
            WHEN Status = 'Completed'
            THEN SalesAmount
            ELSE 0
        END
    ) AS CompletedSales
FROM Sales;

Analysts use conditional aggregation for KPI reporting, compliance metrics, financial analysis, customer segmentation, and dashboard datasets.

  • CASE can be placed inside aggregate functions.
  • SUM with CASE enables conditional totals.
  • COUNT with CASE enables conditional counts.
  • Multiple business metrics can be calculated in one query.
  • Conditional aggregation is common in analytical SQL.
Why use CASE inside SUM?

It allows SUM to include only values that meet a specified condition.

Can CASE be used with COUNT?

Yes. CASE can be used with COUNT or SUM to create conditional counts and metrics.

Have you finished this lesson?

Introduction to SQL – All Lessons