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.
Code
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.