Aggregate FILTER For Conditional Counts

Count subsets in one pass with the FILTER clause on aggregates, replacing repeated CASE expressions and extra scans of the same rows.

SqlData Integrity

Code

snippet
WITH orders (customer, amount, status) AS (
    VALUES
        ('ada', 120, 'paid'),
        ('ada', 80, 'refunded'),
        ('bob', 200, 'paid'),
        ('bob', 50, 'pending'),
        ('cy', 300, 'paid')
)
SELECT
    customer,
    count(*) AS total_orders,
    count(*) FILTER (WHERE status = 'paid') AS paid_orders,
    sum(amount) FILTER (WHERE status = 'paid') AS paid_amount,
    avg(amount) FILTER (WHERE status = 'refunded') AS refunded_avg
FROM orders
GROUP BY customer
ORDER BY customer;

How the snippet works

At its core this is a single SELECT statement against orders.

The SQL constructs in play: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause limiting a statement to the rows that qualify; COUNT, SUM, AVG aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Applying it

Run the statement against the orders table.

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`orders` — referenced directly, no join needed.