SQL FILTER clause on aggregates vs CASE inside an aggregate: how they differ and when to prefer FILTER

Quick Overview

Asks how the SQL FILTER clause on aggregate functions works and how it compares with a CASE expression inside the aggregate. Tests NULL handling in aggregates, the edge cases where the two forms return different results, and when engine support or readability should decide.

SQL FILTER clause on aggregates vs CASE inside an aggregate: how they differ and when to prefer FILTER

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Explain the `FILTER` clause on aggregates. How does it compare to using `CASE` inside an aggregate function, and when would you prefer it? ```hint Follow the excluded rows For each form, work out what the aggregate receives from a row that fails the condition, then check what each one returns when no row matches. ``` ### What a Strong Answer Covers - The syntax of `FILTER` and which rows a single aggregate sees with it - How the `CASE` form reaches the same result through NULL handling - The cases where the two forms return different results - How `FILTER` on one aggregate differs from a `WHERE` clause on the whole query - Engine support and readability as the deciding factors ### Follow-up Questions - What does `array_agg(CASE WHEN ... THEN x END)` return that `array_agg(x) FILTER (WHERE ...)` does not? - How would you write the same report on MySQL or SQL Server? - Can `FILTER` be used with a window aggregate, and what would that look like? - When is a plain `WHERE` clause a better choice than several `FILTER` clauses?

Overview: Asks how the SQL FILTER clause on aggregate functions works and how it compares with a CASE expression inside the aggregate. Tests NULL handling in aggregates, the edge cases where the two forms return different results, and when engine support or readability should decide.

General logo
General
Nov 24, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Explain the FILTER clause on aggregates. How does it compare to using CASE inside an aggregate function, and when would you prefer it?

What a Strong Answer Covers Guidance

  • The syntax of FILTER and which rows a single aggregate sees with it
  • How the CASE form reaches the same result through NULL handling
  • The cases where the two forms return different results
  • How FILTER on one aggregate differs from a WHERE clause on the whole query
  • Engine support and readability as the deciding factors

Follow-up Questions Guidance

  • What does array_agg(CASE WHEN ... THEN x END) return that array_agg(x) FILTER (WHERE ...) does not?
  • How would you write the same report on MySQL or SQL Server?
  • Can FILTER be used with a window aggregate, and what would that look like?
  • When is a plain WHERE clause a better choice than several FILTER clauses?