CodeBlanks Logo Icon CodeBlanks

FILTER clause

Learn the FILTER keyword.

FILTER clause

The FILTER clause makes an aggregate conditional. More readable than CASE.

SELECT
  SUM(amount) FILTER (WHERE category = 'Kitap') AS Kitap,
  SUM(amount) FILTER (WHERE category = 'Elektronik') AS Elektronik
FROM sales;

Supported by PostgreSQL and SQLite.

SUM(amount) FILTER (WHERE category = 'Kitap') AS Kitap, … is selected from sales.

FILTER clause — details

FILTER goes after the aggregate. It gives conditional sums without writing CASE.

FILTER is supported in PostgreSQL and SQLite; MySQL lacks it, so there you get the same result with SUM(CASE WHEN … THEN amount END).

Practice FILTER clause

Write a conditional sum with SUM(amount) FILTER (WHERE category = 'Kitap').

Starter code

query.sql
-- with filter
SELECT
  SUM(amount)

Sample solution

query.sql
SELECT
  SUM(amount) FILTER (WHERE category = 'Kitap') AS Kitap,
  SUM(amount) FILTER (WHERE category = 'Elektronik') AS Elektronik
FROM sales;

Expected output

Kitap
200

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 FILTER clause: match the terms

Term Meaning
FILTER conditional
CASE alternative
SUM sum
readable clean

2 Add FILTER

Question
SUM(amount) ____ (WHERE category = 'Kitap') AS Kitap
Answer
SUM(amount) FILTER (WHERE category = 'Kitap') AS Kitap

Explanation: FILTER (WHERE …) runs an aggregate only on the rows that meet the condition.

3 What does FILTER do?

  • Sorting
  • A conditional aggregate Correct answer
  • Grouping
  • Filtering

Explanation: FILTER makes an aggregate conditional.

All lessons in Advanced