PostgreSQL 18 reference · Aggregate Functions
PostgreSQL FILTER Clause for Aggregates
Restrict which rows one aggregate sees with FILTER (WHERE …), so one query can count several conditions.
PostgreSQL 18 Since 9.4
Syntax
aggregate(...) FILTER (WHERE condition)
Parameters
| Parameter | Description |
|---|---|
condition |
Only rows where it is true are aggregated. |
Return value
The aggregate's result.
Examples
SELECT count(*) AS all_orders,
count(*) FILTER (WHERE status = 'delivered') AS delivered,
count(*) FILTER (WHERE status = 'pending') AS pending
FROM orders;
Output
all_orders | delivered | pending
------------+-----------+---------
12 | 7 | 2
(1 row)Run this on your computer — see “Get Started” for setup.
SELECT department,
round(avg(salary) FILTER (WHERE hire_date >= DATE '2022-01-01')) AS avg_recent_hires
FROM employees
GROUP BY department
ORDER BY department;
Output
department | avg_recent_hires -------------+------------------ Engineering | 113500 Management | NULL Sales | 88000 Support | 65000 (4 rows)
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| PostgreSQL 9.4 | Added |
Related
COUNT()· Count rows: count(*) counts every row, count(x) skips NULLs, and count(DISTINCT x) counts unique values. Returns bigint.CASE· Choose a value from conditions: CASE WHEN cond THEN result … ELSE default END, usable anywhere an expression is.- SQL Aggregate Functions · tutorial
- SQL GROUP BY · tutorial