Function or operator · Grouping and calculating

FILTER (WHERE ...) in SQL aggregates

FILTER (WHERE ...) limits the rows of one particular aggregate without excluding them from the query's other calculations.

Example

We want three measures in a single row: all orders, how many are shipped, and the total amount of the shipped ones only.

SQL checked on SQLite 3.46.1
SELECT COUNT(*) AS orders,
       COUNT(*) FILTER (WHERE status = 'shipped') AS shipped,
       ROUND(SUM(total) FILTER (WHERE status = 'shipped'), 2) AS shipped_amount
FROM orders;

All 18 rows reach COUNT(*). Only the 9 rows with status shipped reach the second COUNT and the SUM that is filtered.

How it is used

PostgreSQL documents FILTER as part of an aggregate expression. SQLite also supports a clause FILTER and includes in the aggregate only the rows for which the expression is true.

What changes from case to case

FILTER vs WHERE, HAVING and CASE

What each option filters
ToolWhat it decidesWhen it helps
WHEREWhich rows enter the query before groupingThe condition must apply to every calculation
FILTERWhich rows a particular aggregate receivesYou need several conditional metrics in the same row
HAVINGWhich groups remain after aggregatingYou are filtering groups on an aggregate result
CASE inside the aggregateWhat value each row contributes to the calculationYou want an explicit, widely portable pattern

The pattern already explained in SUM(CASE WHEN ...) can solve many of the same problems. FILTER makes it clear that the condition belongs to the aggregate, but you should not assume every engine accepts the same syntax.

FILTER also works with GROUP BY

Counts per customer
SELECT customer_id,
       COUNT(*) AS orders,
       COUNT(*) FILTER (WHERE status = 'shipped') AS shipped
FROM orders
GROUP BY customer_id
ORDER BY customer_id;

Each output row represents one customer. Within each group, the first count uses every row and the second only the shipped ones.

Key differences between engines

PostgreSQL includes FILTER (WHERE ...) in the syntax of its aggregate expressions. SQLite documents the same idea in its aggregate function syntax. For other engines, check their documentation before copying this form word for word.