Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 98/ 160
05. Window Functions & Analytical SQL

FILTER (WHERE ...) Clause with Aggregates & Window Functions

Conditionally aggregate with FILTER (WHERE ...) instead of CASE wrappers.

IntermediateFILTER WHERE · Conditional Agg3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Average order value, paid orders onlyQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  customer_id,3  COUNT(*) AS orders,4  AVG(amount) FILTER (5    WHERE6      status = 'paid'7  ) AS avg_paid_amount8FROM9  orders10GROUP BY11  customer_id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
customer_idordersavg_paid_amount
423650
772425
1051NULL

Note: Illustrative customers; customer 105 has no paid order, so the filtered AVG returns NULL.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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).

Running paid spend per customerQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  customer_id,4  status,5  SUM(amount) FILTER (6    WHERE7      status = 'paid'8  ) OVER (9    PARTITION BY10      customer_id11    ORDER BY12      created_at,13      id14  ) AS paid_so_far15FROM16  orders;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/16
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
idcustomer_idstatuspaid_so_far
50142paid300
50742refunded300
51842paid850
51277pendingNULL

Note: Illustrative running paid totals; a non-paid first row can leave the partition total NULL until a paid row appears.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: FILTER works with windows too; use CASE where FILTER isn't supported.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Requirement

List the metrics

Write down each count or total and the condition it applies to.

Focus at this step

all orders · paid · refunded · paid revenue

What to watch at this step
One
condition each
Tip: use ← → to move between steps

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

FILTER (WHERE …)
Best for: Filtered metrics in PostgreSQL, SQLite, DuckDB

Strengths: Clear intent; no ELSE-0 trap; works with windows.

Watch out: Not supported in MySQL or SQL Server.

CASE inside aggregates
Best for: Portable SQL

Strengths: Works everywhere.

Watch out: Verbose and easy to get subtly wrong with COUNT.

Separate queries per metric
Best for: Metrics from different tables

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?
Interview tip: Show a three-metric query with FILTER, then its CASE translation without ELSE. It demonstrates both the clean syntax and awareness of the classic bug.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Named Windows (WINDOW w AS (...)) for Cleaner Queries
Next topic
GROUPING SETS, ROLLUP & CUBE for Multi-Level Subtotals