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
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
CASEinside the aggregate (aggregates ignoreNULL) but is more readable. NoteSUMwithCASE ... ELSE 0returns 0 instead of NULL when no rows match.Prefer
FILTERon PostgreSQL or SQLite. UseCASEfor portability (MySQL and SQL Server lack it).