AI Hints
Home›PostgreSQL Tutorial›Joins, LATERAL and FILTER
PostgreSQL · Lesson 27 of 120

Aggregates and FILTER

Count only some rows.

⏱ 2 min read▶ Video at 22:49🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

For each year, how many orders were delivered, returned, or cancelled? You could write three queries. Filter lets one aggregate count only certain rows.

  • Delivered?
  • Returned?
  • One query

Counts by status

Count star counts all orders. Count star filter where status is returned counts only returned ones. Same for cancelled. Run it. A neat summary per year.

query.sqlsql
SELECT extract(year FROM order_date) AS year,
       count(*)                                     AS orders,
       count(*) FILTER (WHERE status = 'returned')  AS returned,
       count(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders
GROUP BY year
ORDER BY year;
Output
 year | orders | returned | cancelled
------+--------+----------+-----------
 2024 |    559 |       22 |        40
 2025 |   1039 |       41 |       100
(2 rows)

Aggregate helpers

Filter works with any aggregate, like sum or average. String agg joins text from many rows. Bool or and bool and test many booleans. And percentile cont finds medians.

keyvalue
FILTER (WHERE)any aggregate
string_aggjoin text
bool_or / bool_andany / all
percentile_contmedian

Summary

Filter lets one aggregate count only some rows, for tidy summaries. Next, subtotals with rollup.

Key takeaways
  • FILTER
  • count(*)
  • Summaries
Next up: GROUPING SETS and ROLLUP — subtotals