Bird
Raised Fist0
SQLquery~10 mins

Conditional aggregation pattern in SQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Conditional aggregation pattern
Start with data table
↓
Apply condition inside aggregation
↓
Aggregate values meeting condition
↓
Return aggregated result
↓
End
The flow shows how SQL applies a condition inside an aggregate function to summarize data selectively.
Execution Sample
SQL
SELECT
  COUNT(CASE WHEN status = 'active' THEN 1 END) AS active_count,
  SUM(CASE WHEN amount > 100 THEN amount ELSE 0 END) AS big_sales
FROM sales;
This query counts active statuses and sums sales amounts over 100 from the sales table.
Execution Table
StepRow DataCondition (status='active')Count ActionCondition (amount>100)Sum ActionRunning CountRunning Sum
1{status: 'active', amount: 150}TrueCount +1TrueSum +1501150
2{status: 'inactive', amount: 90}FalseCount +0FalseSum +01150
3{status: 'active', amount: 200}TrueCount +1TrueSum +2002350
4{status: 'active', amount: 50}TrueCount +1FalseSum +03350
5{status: 'inactive', amount: 300}FalseCount +0TrueSum +3003650
6{status: 'active', amount: 120}TrueCount +1TrueSum +1204770
ExitNo more rows----Final count=4Final sum=770
💡 All rows processed; aggregation complete.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6Final
active_count01123344
big_sales0150150350350650770770
Key Moments - 2 Insights
Why does the count only increase when status is 'active'?
Because the COUNT uses CASE to include only rows where status='active' (see execution_table rows 1,3,4,6). Rows with other statuses add zero to count.
Why does the sum only add amounts greater than 100?
The SUM uses CASE to add amount only if amount>100, else adds 0 (see execution_table rows 1,3,5,6). Amounts 90 and 50 do not increase sum.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the active_count after processing row 4?
A3
B2
C4
D1
💡 Hint
Check the 'Running Count' column at step 4 in execution_table.
At which step does the big_sales sum first exceed 300?
AStep 4
BStep 3
CStep 5
DStep 6
💡 Hint
Look at the 'Running Sum' column in execution_table to find when sum passes 300.
If the condition for counting changed to status='inactive', what would active_count be after step 6?
A3
B4
C2
D1
💡 Hint
Count how many rows have status='inactive' in the Row Data column.
Concept Snapshot
Conditional aggregation uses CASE inside aggregate functions.
Example: COUNT(CASE WHEN condition THEN 1 END) counts rows meeting condition.
SUM(CASE WHEN condition THEN value ELSE 0 END) sums values meeting condition.
This lets you summarize data selectively in one query.
Useful for counting or summing based on filters without WHERE.
Full Transcript
This visual execution shows how SQL performs conditional aggregation by applying conditions inside aggregate functions like COUNT and SUM. Each row is checked against conditions: if status equals 'active', the count increases by one; if amount is greater than 100, the sum adds that amount. The execution table tracks each row's data, condition results, and running totals. The variable tracker shows how active_count and big_sales change after each row. Key moments clarify why only certain rows affect counts or sums. The quiz tests understanding of running totals and condition effects. The snapshot summarizes the pattern: use CASE inside aggregates to count or sum conditionally in one query.

Practice

(1/5)
1. What does conditional aggregation in SQL allow you to do?
SUM(CASE WHEN condition THEN value ELSE 0 END)
easy
A. Delete rows that meet a condition
B. Join two tables based on a condition
C. Create a new table from existing data
D. Calculate sums or counts based on specific conditions within one query

Solution

  1. Step 1: Understand conditional aggregation concept

    Conditional aggregation uses CASE inside aggregate functions like SUM or COUNT to selectively include values based on conditions.
  2. Step 2: Identify what it achieves

    This lets you calculate sums or counts for different conditions in one query without multiple scans.
  3. Final Answer:

    Calculate sums or counts based on specific conditions within one query -> Option D
  4. Quick Check:

    Conditional aggregation = selective sums/counts [OK]
Hint: Think: aggregate + CASE filters rows inside one query [OK]
Common Mistakes:
  • Confusing conditional aggregation with JOIN operations
  • Thinking it creates or deletes tables
  • Assuming it filters rows outside aggregation
2. Which of the following is the correct syntax using COUNT for counting only rows where status = 'active' using conditional aggregation?
easy
A. COUNT(CASE WHEN status = 'active' THEN 1 ELSE NULL END)
B. COUNT(CASE status = 'active' THEN 1 END)
C. SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END)
D. COUNT(IF status = 'active' THEN 1 ELSE 0 END)

Solution

  1. Step 1: Recall correct CASE syntax inside COUNT

    The CASE expression must have WHEN condition THEN value ELSE NULL END for COUNT to count only matching rows.
  2. Step 2: Check each option

    COUNT(CASE WHEN status = 'active' THEN 1 ELSE NULL END) uses correct CASE syntax with ELSE NULL, so COUNT counts only 'active' rows. COUNT(CASE status = 'active' THEN 1 END) misses WHEN keyword. SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) uses SUM, not COUNT. COUNT(IF status = 'active' THEN 1 ELSE 0 END) uses invalid IF syntax.
  3. Final Answer:

    COUNT(CASE WHEN status = 'active' THEN 1 ELSE NULL END) -> Option A
  4. Quick Check:

    COUNT + CASE WHEN ... THEN 1 ELSE NULL END [OK]
Hint: Use ELSE NULL inside CASE for COUNT to skip rows [OK]
Common Mistakes:
  • Omitting WHEN keyword in CASE
  • Using SUM instead of COUNT for counting rows
  • Using ELSE 0 which counts zeros as rows
3. Given the table sales with columns region and amount, what is the output of this query?
SELECT region, SUM(CASE WHEN amount > 100 THEN amount ELSE 0 END) AS big_sales FROM sales GROUP BY region;
medium
A. Sum of sales amounts greater than 100 per region
B. Count of sales with amount greater than 100 per region
C. Sum of all sales amounts per region
D. Sum of sales amounts less than or equal to 100 per region

Solution

  1. Step 1: Analyze the CASE inside SUM

    The CASE returns amount if amount > 100, else 0. So only amounts above 100 contribute to the sum.
  2. Step 2: Understand GROUP BY effect

    The query groups rows by region, summing only big sales (amount > 100) per region.
  3. Final Answer:

    Sum of sales amounts greater than 100 per region -> Option A
  4. Quick Check:

    SUM with CASE filters amounts > 100 [OK]
Hint: CASE filters values inside SUM to include only big sales [OK]
Common Mistakes:
  • Thinking it sums all sales, ignoring condition
  • Confusing SUM with COUNT
  • Assuming it sums small sales instead
4. Identify the error in this SQL query using conditional aggregation:
SELECT department, COUNT(CASE WHEN salary > 50000 THEN 1 ELSE 0 END) AS high_earners FROM employees GROUP BY department;
medium
A. SUM should be used instead of COUNT
B. COUNT counts zeros, so it counts all rows, not just high earners
C. CASE syntax is invalid
D. Missing GROUP BY clause

Solution

  1. Step 1: Understand COUNT behavior with CASE

    COUNT counts all non-NULL values. Here ELSE 0 returns zero, which is counted as a value, so all rows count.
  2. Step 2: Identify correct fix

    To count only high earners, ELSE should be NULL so those rows are ignored by COUNT.
  3. Final Answer:

    COUNT counts zeros, so it counts all rows, not just high earners -> Option B
  4. Quick Check:

    COUNT counts non-NULL, zero is counted [OK]
Hint: Use ELSE NULL to exclude rows from COUNT [OK]
Common Mistakes:
  • Using ELSE 0 causes wrong counts
  • Confusing COUNT with SUM
  • Ignoring that zero is counted by COUNT
5. You want to find the total sales and the count of sales above 1000 for each product in one query. Which SQL query correctly uses conditional aggregation?
hard
A. SELECT product, COUNT(amount) AS total_sales, SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product;
B. SELECT product, SUM(CASE WHEN amount > 1000 THEN amount ELSE 0 END) AS total_sales, COUNT(amount) AS big_sales_count FROM sales GROUP BY product;
C. SELECT product, SUM(amount) AS total_sales, SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product;
D. SELECT product, SUM(amount) AS total_sales, COUNT(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product;

Solution

  1. Step 1: Identify total sales calculation

    Total sales is sum of all amounts, so SUM(amount) is correct.
  2. Step 2: Identify count of sales above 1000

    Counting sales above 1000 can be done by summing 1 for each qualifying row and 0 otherwise, so SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) works.
  3. Step 3: Check each option

    SELECT product, SUM(amount) AS total_sales, COUNT(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product; uses COUNT with ELSE 0 which counts all rows incorrectly; SELECT product, SUM(CASE WHEN amount > 1000 THEN amount ELSE 0 END) AS total_sales, COUNT(amount) AS big_sales_count FROM sales GROUP BY product; incorrectly sums only amounts above 1000 for total_sales; SELECT product, COUNT(amount) AS total_sales, SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product; swaps SUM and COUNT incorrectly; SELECT product, SUM(amount) AS total_sales, SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product; correctly sums total sales and counts big sales using SUM with CASE.
  4. Final Answer:

    SELECT product, SUM(amount) AS total_sales, SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product; -> Option C
  5. Quick Check:

    SUM for totals, SUM(CASE) for conditional counts [OK]
Hint: Use SUM(CASE) for conditional counts, SUM(column) for totals [OK]
Common Mistakes:
  • Using COUNT with ELSE 0 which counts all rows
  • Summing only filtered amounts for total sales
  • Mixing COUNT and SUM incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard