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

Last updated 13 July 2026

  • agg(x) FILTER (WHERE cond) makes an aggregate consider only matching rows, so several conditional metrics can be computed in one pass.

  • It is equivalent to a CASE inside the aggregate (aggregates ignore NULL) but is more readable. Note SUM with CASE ... ELSE 0 returns 0 instead of NULL when no rows match.

  • Prefer FILTER on PostgreSQL or SQLite. Use CASE for portability (MySQL and SQL Server lack it).

  • https://duckdb.org/docs/lts/sql/query_syntax/filter
  • https://duckdb.org/docs/lts/sql/functions/aggregates
  • https://www.youtube.com/watch?v=Qls1Ixxis18
  • https://motherduck.com/glossary/filter-clause/
  • https://theartofpostgresql.com/yesql/aggregation/filter-clause/
All Advanced SQL interview questions