// window reference

SQL FILTER clause with window aggregates

FILTER (WHERE condition) restricts which rows the aggregate sees, inside or outside a window: conditional sums and counts without CASE nesting.

Categoria
Janela
Returns
conditional aggregate
In this category
64 of 79

Sintaxe

COUNT(*) FILTER (WHERE status = 'won') OVER (PARTITION BY rep)

Suporte a mecanismos

MotorSupportNotas
SQL Server Not built in not supported, including SQL Server 2025; use CASE inside the aggregate
PostgreSQL Sim PostgreSQL 9.4+
MySQL Not built in not supported; use CASE inside the aggregate
SQLite Sim SQLite 3.30+; rejected on built-in (non-aggregate) window functions like ROW_NUMBER
Oracle Sim Oracle AI Database 26ai, release update 23.26.1+; CASE on 23ai and earlier

Exemplos

PostgreSQL

SELECT rep, deal_id, amount,
       COUNT(*) FILTER (WHERE status = 'won') OVER (PARTITION BY rep) AS wins,
       SUM(amount) FILTER (WHERE status = 'open') OVER (PARTITION BY rep) AS open_amount
FROM deals;

SQL Server

SELECT rep, deal_id,
       SUM(CASE WHEN status = 'won' THEN 1 ELSE 0 END) OVER (PARTITION BY rep) AS wins
FROM deals;

Bom saber

  • FILTER is only valid on aggregate functions: SQLite says 'FILTER clause may only be used with aggregate window functions' for ROW_NUMBER, LAG and the rest, and PostgreSQL rejects them too.
  • The portable equivalent is the CASE aggregate: COUNT(*) FILTER (WHERE status = 'won') becomes SUM(CASE WHEN status = 'won' THEN 1 ELSE 0 END), and SUM(x) FILTER (WHERE c) becomes SUM(CASE WHEN c THEN x END).
  • Keep the ELSE off when translating SUM(x) FILTER: with no matching rows FILTER returns NULL, and SUM(CASE WHEN c THEN x END) also returns NULL, while ELSE 0 would return 0.

Questions about FILTER with OVER

Is FILTER faster than CASE inside the aggregate?

Not in any way you will measure; both are evaluated in the same pass over the window. Use FILTER for readability where it exists.

Can FILTER be used without OVER?

Yes, it works on plain aggregates too (COUNT(*) FILTER (WHERE ...) in a GROUP BY query), which is exactly how the window form composes.

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.