HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlpostgresqlTippending

PostgreSQL FILTER clause for conditional aggregation

Submitted by: @anonymous··
0
Viewed 0 times
FILTERaggregateconditionalcountsumPostgreSQL

Problem

Conditional counting/summing requires CASE WHEN inside aggregate functions, which is verbose.

Solution

Use the FILTER clause for cleaner conditional aggregates:

SELECT
count(*) AS total_orders,
count(*) FILTER (WHERE status = 'completed') AS completed,
count(*) FILTER (WHERE status = 'pending') AS pending,
sum(amount) FILTER (WHERE status = 'completed') AS completed_revenue,
avg(amount) FILTER (WHERE created_at > now() - interval '30 days') AS recent_avg
FROM orders;

-- Equivalent CASE WHEN (more verbose):
-- count(CASE WHEN status = 'completed' THEN 1 END) AS completed

Why

FILTER is PostgreSQL-specific but far more readable than CASE WHEN for conditional aggregation.

Revisions (0)

No revisions yet.