// aggregates reference

SQL FILTER clause

Attaches its own WHERE to a single aggregate so one SELECT can carry several conditional aggregates.

Kategorie
Aggregates
Returns
depends on the aggregate
In this category
16 of 52

Syntax

COUNT(x) FILTER (WHERE cond) | SUM(x) FILTER (WHERE cond)

Engine-Unterstützung

EngineSupportNotizen
SQL Server Not built in No built-in equivalent.
PostgreSQL Ja works on every aggregate, window aggregates included
MySQL Not built in use SUM(CASE WHEN cond THEN x END)
SQLite Ja 3.30+
Oracle Ja Oracle AI Database 26ai, release update 23.26.1+; SUM(CASE WHEN cond THEN x END) on 23ai and earlier

Beispiele

PostgreSQL

SELECT COUNT(*) FILTER (WHERE status = 'open') AS open_count, COUNT(*) FILTER (WHERE status = 'closed') AS closed_count FROM tickets;

SQLite

SELECT SUM(amount) FILTER (WHERE kind = 'refund') AS refunds FROM payments;

Any engine

SELECT SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) AS open_count, SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) AS closed_count FROM tickets;

Gut zu wissen

  • Rows failing the predicate are excluded from that one aggregate but still counted by the others in the same SELECT.
  • The CASE fallback works because CASE without ELSE yields NULL and aggregates ignore NULLs, so SUM(CASE WHEN cond THEN x END) equals the FILTER form.
  • PostgreSQL, SQLite and Oracle 23.26.1+ accept FILTER on window aggregates too: COUNT(*) FILTER (WHERE x > 1) OVER (PARTITION BY g).

Questions about FILTER

How is FILTER different from WHERE?

WHERE drops whole rows before grouping; FILTER drops rows from a single aggregate while the group and the other aggregates keep them.

Which engines support FILTER?

PostgreSQL on all aggregates, SQLite since 3.30, and Oracle from release update 23.26.1. MySQL, SQL Server and older Oracle releases need the SUM(CASE WHEN ...) pattern.

Can FILTER be used with COUNT(*)?

Yes: COUNT(*) FILTER (WHERE cond) counts only the rows matching the predicate inside each group.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.