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?
✗ Incorrect
FILTER applies a condition inside aggregate functions to include only rows that meet the condition.
Which of these is a valid use of FILTER in PostgreSQL?
✗ Incorrect
The correct syntax is aggregate_function FILTER (WHERE condition).
How does FILTER improve readability compared to CASE WHEN inside aggregates?
✗ Incorrect
FILTER keeps the condition outside the aggregate function, making the query easier to read.
Can you use FILTER with SUM and COUNT in the same query?
✗ Incorrect
Multiple FILTER clauses can be used with different aggregate functions and conditions.
What does this query do? SELECT COUNT(*) FILTER (WHERE active) FROM users;
✗ Incorrect
FILTER restricts the count to rows where the condition (active) is true.
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.