FILTER (WHERE ...) Clause with Aggregates & Window Functions
Conditionally aggregate with FILTER (WHERE ...) instead of CASE wrappers.
In plain words
FILTER lets each total count only the rows it cares about, while other totals in the same query count everything.
Think of it like…
Counting a classroom with sticky notes: "how many students in total", "how many wearing glasses", "how many left-handed". Each count looks at the same students but only ticks the ones that fit its own question.
Where you’ve seen it
A daily status report: SELECT created_at::date AS day, COUNT(*) AS orders, COUNT(*) FILTER (WHERE status = 'paid') AS paid, COUNT(*) FILTER (WHERE status = 'refunded') AS refunded, SUM(amount) FILTER (WHERE status = 'paid') AS paid_revenue FROM orders GROUP BY 1 ORDER BY 1;
Words you’ll hear
- FILTER (WHERE …)
- Applies a condition to the rows one aggregate sees.
- Conditional aggregation
- Several filtered metrics from one pass over the data.
- CASE equivalent
- SUM(CASE WHEN cond THEN x END) in databases without FILTER.
- Window FILTER
- SUM(x) FILTER (WHERE …) OVER (…) for filtered running totals.
Visual diagram
Theory & example queries
FILTER vs WHERE vs CASE
WHERE removes rows before aggregation, so it affects every aggregate in the query. FILTER applies only to the aggregate it's attached to, so one query can report totals, paid counts and refunded counts together. It works with every aggregate: COUNT, SUM, AVG, MIN, MAX, ARRAY_AGG, STRING_AGG.
The CASE equivalent is COUNT(CASE WHEN status = 'paid' THEN 1 END) or SUM(CASE WHEN status = 'paid' THEN amount END). It's portable, but people often write COUNT(CASE WHEN … THEN 1 ELSE 0 END), which counts every row because 0 isn't NULL. FILTER avoids that class of bug, and its performance is the same.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT customer_id, COUNT(*) AS orders, AVG(amount) FILTER ( WHERE status = 'paid' ) AS avg_paid_amountFROM ordersGROUP BY customer_id;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| customer_id | orders | avg_paid_amount |
|---|---|---|
| 42 | 3 | 650 |
| 77 | 2 | 425 |
| 105 | 1 | NULL |
Note: Illustrative customers; customer 105 has no paid order, so the filtered AVG returns NULL.
Key takeaway: WHERE filters for everything; FILTER filters for one aggregate.
Window aggregates and portability
FILTER also works with aggregate window functions, which gives running totals of a subset: SUM(amount) FILTER (WHERE status = 'paid') OVER (PARTITION BY customer_id ORDER BY created_at) is a customer's running paid spend on every order row, including unpaid ones.
FILTER is standard SQL (SQL:2003) and supported by PostgreSQL 9.4+, SQLite 3.30+, DuckDB and some warehouses. For MySQL, SQL Server or portable code, use the CASE form, and for counts write it without ELSE (or with SUM and ELSE 0).
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT id, customer_id, status, SUM(amount) FILTER ( WHERE status = 'paid' ) OVER ( PARTITION BY customer_id ORDER BY created_at, id ) AS paid_so_farFROM orders;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output4 sample rows
| id | customer_id | status | paid_so_far |
|---|---|---|---|
| 501 | 42 | paid | 300 |
| 507 | 42 | refunded | 300 |
| 518 | 42 | paid | 850 |
| 512 | 77 | pending | NULL |
Note: Illustrative running paid totals; a non-paid first row can leave the partition total NULL until a paid row appears.
Key takeaway: FILTER works with windows too; use CASE where FILTER isn't supported.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
List the metrics
Write down each count or total and the condition it applies to.
all orders · paid · refunded · paid revenue
When to use it & trade-offs
What it is
The FILTER (WHERE …) clause restricts which rows a single aggregate counts: COUNT(*) FILTER (WHERE status = 'paid') counts only paid orders, alongside other aggregates in the same query. It does the same job as SUM(CASE WHEN … THEN 1 ELSE 0 END) but reads more clearly, and it works on window aggregates too. PostgreSQL, SQLite and DuckDB support it; MySQL and SQL Server don't.
Why it matters: Dashboards are full of "how many of each" metrics side by side, and the CASE-inside-aggregate version is easy to get subtly wrong (the COUNT … ELSE 0 bug). FILTER says exactly what it means, which makes reports easier to read and review.
When to reach for it
- Status breakdowns in reports
- Conversion-style metrics (paid ÷ total) in one query
- Filtered running totals
When to avoid or be careful
- Using WHERE when only one metric should be filtered
- COUNT(CASE … ELSE 0 END)
- FILTER in queries that must run on MySQL or SQL Server
FILTER vs CASE inside aggregates vs separate queries
Strengths: Clear intent; no ELSE-0 trap; works with windows.
Watch out: Not supported in MySQL or SQL Server.
Strengths: Works everywhere.
Watch out: Verbose and easy to get subtly wrong with COUNT.
Strengths: Each query is simple.
Watch out: Several scans; must be joined back together.
Interview signals & numbers to know
When this topic comes up
- “Count paid and refunded orders per day”
- “Conversion rate in one query”
- Conditional aggregation
- Pivot-style reports
- COUNT CASE bugs
Benchmarks & rules of thumb
- PostgreSQL 9.4
- FILTER introduced
- SQLite 3.30
- FILTER support
- 0
- FILTER support in MySQL
Common mistakes & follow-ups
Common interview mistakes
- Putting status = 'paid' in WHERE and accidentally filtering the total count too.
- Translating FILTER to COUNT(CASE … ELSE 0 END) for MySQL and counting every row.
- Expecting FILTER to work in SQL Server.
Likely interviewer follow-ups
- What's the difference between WHERE and FILTER?
- How would you write the same metrics in MySQL?
- How would you compute the paid-order conversion rate per day in one query?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply FILTER (WHERE ...) Clause with Aggregates & Window Functions with hands-on SQL practice and interview Q&A.