0
0
PostgreSQLquery~5 mins

FILTER clause for conditional aggregation in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the FILTER clause do in SQL aggregation?
The FILTER clause lets you apply a condition to an aggregate function, so it only counts or sums rows that meet that condition.
Click to reveal answer
beginner
Write a simple example of using FILTER with COUNT in PostgreSQL.
SELECT COUNT(*) FILTER (WHERE status = 'active') AS active_count FROM users;
Click to reveal answer
intermediate
Why use FILTER instead of CASE WHEN inside aggregate functions?
FILTER is clearer and easier to read because it separates the condition from the aggregate function, making queries simpler and more maintainable.
Click to reveal answer
intermediate
Can you use multiple FILTER clauses in one SELECT statement?
Yes, you can use multiple FILTER clauses with different conditions on different aggregate functions in the same query.
Click to reveal answer
beginner
What will this query return? SELECT SUM(amount) FILTER (WHERE type = 'sale') FROM orders;
It returns the total sum of the 'amount' column but only for rows where the 'type' is 'sale'.
Click to reveal answer
What is the purpose of the FILTER clause in SQL aggregation?
ATo apply a condition to aggregate functions
BTo filter rows before aggregation
CTo sort the results after aggregation
DTo join tables conditionally
Which of these is a valid use of FILTER in PostgreSQL?
ACOUNT(*) WHERE FILTER age > 30
BCOUNT(*) FILTER (WHERE age > 30)
CCOUNT(FILTER WHERE age > 30)
DFILTER COUNT(*) WHERE age > 30
How does FILTER improve readability compared to CASE WHEN inside aggregates?
AIt makes queries longer
BIt replaces GROUP BY
CIt requires more nested queries
DIt separates condition from aggregation clearly
Can you use FILTER with SUM and COUNT in the same query?
AYes, with different conditions
BNo, only one FILTER per query
COnly with SUM, not COUNT
DOnly with COUNT, not SUM
What does this query do? SELECT COUNT(*) FILTER (WHERE active) FROM users;
ACounts rows where active is false
BCounts all rows ignoring active
CCounts only rows where active is true
DCounts rows with NULL active
Explain how the FILTER clause works in SQL aggregation and why it is useful.
Think about how you count or sum only some rows based on a condition.
You got /4 concepts.
    Write a SQL query using FILTER to count how many orders have status 'completed' and sum amounts for 'pending' orders.
    Use FILTER clause separately for COUNT and SUM with different conditions.
    You got /3 concepts.