Bird
Raised Fist0
PostgreSQLquery~20 mins

FILTER clause for conditional aggregation in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FILTER Clause Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Calculate conditional sums using FILTER clause
Given a table sales with columns region, amount, and category, what is the output of this query?
SELECT region,
SUM(amount) FILTER (WHERE category = 'A') AS sum_a,
SUM(amount) FILTER (WHERE category = 'B') AS sum_b
FROM sales
GROUP BY region
ORDER BY region;

Assume the table data is:
region | amount | category
-------+--------+---------
East   | 100    | A
East   | 200    | B
West   | 150    | A
West   | 50     | B
West   | 100    | C
A[{"region": "East", "sum_a": 100, "sum_b": 200}, {"region": "West", "sum_a": 150, "sum_b": 50}]
B[{"region": "East", "sum_a": 100, "sum_b": 200}, {"region": "West", "sum_a": 150, "sum_b": 0}]
C[{"region": "East", "sum_a": 100, "sum_b": 0}, {"region": "West", "sum_a": 150, "sum_b": 50}]
D[{"region": "East", "sum_a": 300, "sum_b": 200}, {"region": "West", "sum_a": 150, "sum_b": 150}]
Attempts:
2 left
💡 Hint
Remember FILTER applies the condition only to the aggregation inside it.
🧠 Conceptual
intermediate
1:30remaining
Understanding FILTER clause behavior with NULL values
Consider a table orders with columns customer_id, status, and total. What does the FILTER clause do when the condition evaluates to NULL?
SELECT customer_id,
COUNT(*) FILTER (WHERE status = 'completed') AS completed_orders
FROM orders
GROUP BY customer_id;

If some rows have status as NULL, how are they counted?
ARows with NULL status are counted in completed_orders because NULL is treated as true.
BRows with NULL status are not counted in completed_orders because the condition evaluates to NULL, which is treated as false.
CRows with NULL status cause the query to fail with an error.
DRows with NULL status are counted as zero but included in the total count.
Attempts:
2 left
💡 Hint
FILTER counts only rows where the condition is true, NULL is not true.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in FILTER clause usage
Which of the following queries will cause a syntax error in PostgreSQL?
SELECT department,
SUM(salary) FILTER (category = 'Engineering')
FROM employees
GROUP BY department;
ASyntax error because GROUP BY is missing a column.
BThe query runs without error and returns sums filtered by category.
CSyntax error because SUM cannot be used with FILTER clause.
DSyntax error because FILTER clause requires WHERE keyword before the condition.
Attempts:
2 left
💡 Hint
Check the FILTER clause syntax carefully.
❓ optimization
advanced
2:00remaining
Optimize query using FILTER clause instead of CASE
You have this query:
SELECT region,
SUM(CASE WHEN category = 'A' THEN amount ELSE 0 END) AS sum_a,
SUM(CASE WHEN category = 'B' THEN amount ELSE 0 END) AS sum_b
FROM sales
GROUP BY region;

Which rewritten query using FILTER clause is equivalent and potentially more efficient?
ASELECT region, SUM(amount) FILTER (WHERE category = 'A') AS sum_a, SUM(amount) FILTER (WHERE category = 'B') AS sum_b FROM sales GROUP BY region;
BSELECT region, SUM(amount) WHERE category = 'A' AS sum_a, SUM(amount) WHERE category = 'B' AS sum_b FROM sales GROUP BY region;
CSELECT region, SUM(amount) FILTER (category = 'A') AS sum_a, SUM(amount) FILTER (category = 'B') AS sum_b FROM sales GROUP BY region;
DSELECT region, SUM(amount) CASE WHEN category = 'A' THEN amount END AS sum_a, SUM(amount) CASE WHEN category = 'B' THEN amount END AS sum_b FROM sales GROUP BY region;
Attempts:
2 left
💡 Hint
FILTER clause requires WHERE keyword and condition inside parentheses.
🔧 Debug
expert
2:30remaining
Debug unexpected results with FILTER clause and NULLs
A developer wrote this query:
SELECT product_id,
COUNT(*) FILTER (WHERE status = 'sold') AS sold_count,
COUNT(*) FILTER (WHERE status != 'sold') AS other_count
FROM product_sales
GROUP BY product_id;

But the other_count is unexpectedly low. The status column contains NULL values. Why?
Choose the best explanation.
AThe query fails because NULL values cause COUNT(*) to error inside FILTER.
BThe query counts NULLs in other_count because NULL != 'sold' is true.
CThe condition <code>status != 'sold'</code> excludes NULLs because NULL comparison returns NULL, so those rows are not counted.
DThe query counts NULLs in sold_count because NULL = 'sold' is true.
Attempts:
2 left
💡 Hint
Remember how NULL behaves in SQL comparisons.

Practice

(1/5)
1. What does the FILTER clause do in a PostgreSQL aggregate function?
easy
A. It filters the entire table before aggregation starts.
B. It applies a condition to include only certain rows in the aggregation.
C. It changes the grouping columns in the query.
D. It sorts the results after aggregation.

Solution

  1. Step 1: Understand the purpose of FILTER in aggregation

    The FILTER clause allows you to specify a condition inside an aggregate function to include only rows that meet that condition.
  2. Step 2: Compare with other options

    FILTER does not filter the whole table before aggregation, nor does it change grouping or sort results. It only limits rows counted or summed inside the aggregate.
  3. Final Answer:

    It applies a condition to include only certain rows in the aggregation. -> Option B
  4. Quick Check:

    FILTER = condition inside aggregate [OK]
Hint: FILTER applies conditions inside aggregates, not on whole table [OK]
Common Mistakes:
  • Thinking FILTER filters rows before aggregation
  • Confusing FILTER with WHERE clause
  • Assuming FILTER changes GROUP BY columns
2. Which of the following is the correct syntax to count only rows where status = 'active' using FILTER in PostgreSQL?
easy
A. SELECT COUNT(*) FILTER (WHERE status = 'active') FROM users;
B. SELECT COUNT(*) FROM users FILTER (WHERE status = 'active');
C. SELECT COUNT(*) WHERE FILTER status = 'active' FROM users;
D. SELECT COUNT(*) FILTER WHERE status = 'active' FROM users;

Solution

  1. Step 1: Recall FILTER syntax in aggregate functions

    The correct syntax places FILTER with parentheses and a WHERE clause inside the aggregate function: COUNT(*) FILTER (WHERE condition).
  2. Step 2: Check each option

    SELECT COUNT(*) FILTER (WHERE status = 'active') FROM users; matches the correct syntax. The other options misuse FILTER placement or syntax.
  3. Final Answer:

    SELECT COUNT(*) FILTER (WHERE status = 'active') FROM users; -> Option A
  4. Quick Check:

    FILTER syntax = FILTER (WHERE condition) [OK]
Hint: Use FILTER (WHERE condition) inside aggregate parentheses [OK]
Common Mistakes:
  • Omitting parentheses after FILTER
  • Placing FILTER outside aggregate function
  • Using FILTER without WHERE keyword
3. Given the table sales with columns region and amount, what will this query return?
SELECT region, SUM(amount) FILTER (WHERE amount > 100) AS big_sales FROM sales GROUP BY region;
medium
A. Sum of all sales amounts per region.
B. Count of sales with amount greater than 100 per region.
C. Sum of sales amounts less than or equal to 100 per region.
D. Sum of sales amounts greater than 100 per region.

Solution

  1. Step 1: Understand the FILTER condition in SUM

    The FILTER clause limits the SUM to only rows where amount > 100.
  2. Step 2: Analyze the GROUP BY effect

    The query groups rows by region, then sums only amounts above 100 in each group.
  3. Final Answer:

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

    SUM with FILTER (WHERE amount > 100) = sum of big sales [OK]
Hint: FILTER limits rows inside SUM to amount > 100 [OK]
Common Mistakes:
  • Thinking it sums all amounts, ignoring FILTER
  • Confusing SUM with COUNT
  • Ignoring GROUP BY effect
4. Identify the error in this query:
SELECT department, COUNT(*) FILTER (status = 'active') FROM employees GROUP BY department;
medium
A. Missing WHERE keyword inside FILTER clause.
B. GROUP BY should include status column.
C. COUNT(*) cannot be used with FILTER.
D. FILTER clause must be outside aggregate function.

Solution

  1. Step 1: Check FILTER clause syntax

    FILTER requires a WHERE keyword before the condition: FILTER (WHERE condition).
  2. Step 2: Verify other parts

    GROUP BY on department is correct. COUNT(*) works with FILTER. FILTER must be inside aggregate function.
  3. Final Answer:

    Missing WHERE keyword inside FILTER clause. -> Option A
  4. Quick Check:

    FILTER syntax needs WHERE [OK]
Hint: Always include WHERE inside FILTER parentheses [OK]
Common Mistakes:
  • Omitting WHERE in FILTER
  • Placing FILTER outside aggregate
  • Adding unnecessary columns to GROUP BY
5. You want to find the total sales and the total sales above 500 for each store in one query. Which query correctly uses FILTER to achieve this?
hard
A. SELECT store, SUM(amount) FILTER (WHERE amount > 500) AS total_sales, SUM(amount) AS big_sales FROM sales GROUP BY store;
B. SELECT store, SUM(amount) AS total_sales, COUNT(amount) FILTER (WHERE amount > 500) AS big_sales FROM sales GROUP BY store;
C. SELECT store, SUM(amount) AS total_sales, SUM(amount) FILTER (WHERE amount > 500) AS big_sales FROM sales GROUP BY store;
D. SELECT store, COUNT(amount) AS total_sales, SUM(amount) FILTER (WHERE amount > 500) AS big_sales FROM sales GROUP BY store;

Solution

  1. Step 1: Identify total sales calculation

    Total sales is the sum of all amounts per store, so SUM(amount) without filter is correct.
  2. Step 2: Identify big sales calculation

    Big sales are sums of amounts greater than 500, so SUM(amount) FILTER (WHERE amount > 500) is correct.
  3. Step 3: Check options

    SELECT store, SUM(amount) AS total_sales, SUM(amount) FILTER (WHERE amount > 500) AS big_sales FROM sales GROUP BY store; correctly assigns total_sales and big_sales. The other options mix sums and counts incorrectly or swap columns.
  4. Final Answer:

    SELECT store, SUM(amount) AS total_sales, SUM(amount) FILTER (WHERE amount > 500) AS big_sales FROM sales GROUP BY store; -> Option C
  5. Quick Check:

    SUM with and without FILTER for totals [OK]
Hint: Use SUM(amount) and SUM(amount) FILTER (WHERE ...) together [OK]
Common Mistakes:
  • Swapping filtered and unfiltered sums
  • Using COUNT instead of SUM for amounts
  • Misplacing FILTER clause
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