sqlintermediate
Conditional Aggregation with FILTER / CASE
Compute multiple conditional aggregates in a single query using FILTER or CASE.
sqlPress ⌘/Ctrl + Shift + C to copy
-- PostgreSQL: FILTER clause
SELECT
DATE_TRUNC('month', order_date) AS month,
COUNT(*) AS total_orders,
COUNT(*) FILTER (WHERE status = 'completed') AS completed,
COUNT(*) FILTER (WHERE status = 'cancelled') AS cancelled,
SUM(total) FILTER (WHERE status = 'completed') AS completed_revenue
FROM orders
GROUP BY 1
ORDER BY 1;
-- Standard SQL: CASE inside aggregate
SELECT
department,
COUNT(CASE WHEN salary > 100000 THEN 1 END) AS high_earners,
COUNT(CASE WHEN salary <= 100000 THEN 1 END) AS others,
AVG(CASE WHEN gender = 'F' THEN salary END) AS avg_female_salary,
AVG(CASE WHEN gender = 'M' THEN salary END) AS avg_male_salary
FROM employees
GROUP BY department;Use Cases
- Pivot-style reports
- Multi-dimension aggregation
- KPI dashboards
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqladvanced
GROUPING SETS, CUBE, and ROLLUP
Generate multiple levels of aggregation in a single query with grouping sets.
Best for: Report subtotals
#sql#grouping-sets
sqlbeginner
Aggregate Strings with STRING_AGG / GROUP_CONCAT
Concatenate values from multiple rows into a single string per group.
Best for: Comma-separated lists in reports
#sql#string-agg
sqlbeginner
CASE WHEN Conditional Expressions
Use CASE expressions for conditional logic in SELECT, WHERE, ORDER BY, and aggregations.
Best for: data categorization
#sql#case-when
sqlintermediate
JSON Aggregation and Querying
Aggregate related rows into JSON arrays and query JSONB columns with PostgreSQL native JSON operators.
Best for: API response building
#json#jsonb