0
0
SQLquery~5 mins

Conditional aggregation pattern in SQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the conditional aggregation pattern in SQL?
It is a way to calculate sums, counts, or other aggregates based on conditions inside a single query, using CASE statements inside aggregate functions.
Click to reveal answer
beginner
How do you count rows that meet a condition using conditional aggregation?
Use COUNT(CASE WHEN condition THEN 1 END) or SUM(CASE WHEN condition THEN 1 ELSE 0 END) to count only rows that satisfy the condition.
Click to reveal answer
intermediate
Why use conditional aggregation instead of multiple queries?
It combines multiple conditional counts or sums into one query, making it faster and easier to read, like counting different categories in one go.
Click to reveal answer
beginner
Write a simple example of conditional aggregation to count male and female employees.
SELECT COUNT(CASE WHEN gender = 'M' THEN 1 END) AS male_count, COUNT(CASE WHEN gender = 'F' THEN 1 END) AS female_count FROM employees;
Click to reveal answer
beginner
What happens if the CASE condition is false in conditional aggregation?
The CASE returns NULL or 0 (if ELSE 0 is used), so the aggregate function ignores or does not add that row to the count or sum.
Click to reveal answer
Which SQL function is commonly used with CASE for conditional aggregation?
ASUM
BJOIN
CORDER BY
DGROUP BY
How do you count rows where a condition is true using conditional aggregation?
AWHERE condition
BCOUNT(CASE WHEN condition THEN 1 END)
CGROUP BY condition
DORDER BY condition
What does this SQL snippet do? SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END)
ASums all rows
BCounts inactive rows
CCounts active rows
DFilters rows
Why is conditional aggregation useful?
ATo combine multiple conditional counts or sums in one query
BTo delete rows
CTo create new tables
DTo sort data
What will happen if CASE returns NULL inside an aggregate function like COUNT?
AThe query fails
BNULL is counted as zero
CThe row is counted anyway
DThat row is ignored in the count
Explain how to use the conditional aggregation pattern to count different categories in one SQL query.
Think about how CASE can return values only when conditions are met.
You got /4 concepts.
    Describe the difference between filtering rows with WHERE and counting conditionally with CASE inside aggregation.
    Consider when rows are included or excluded in each method.
    You got /3 concepts.