Aggregation intro

Draft

Aggregates reduce many rows into summaries. GROUP BY decides the level of detail: one row for the whole table, or one row per group.

Count and sum

Aggregate functions collapse many rows into one summary row.

SELECT COUNT(*) AS orders, SUM(total_cents) AS revenue_cents
FROM orders;
ordersrevenue_cents
511700
Aggregate  (cost=22.15..22.16 rows=1 width=16)
  ->  Seq Scan on orders  (cost=0.00..18.10 rows=810 width=4)

Group by city

GROUP BY returns one summary row for each distinct city.

SELECT city, COUNT(*) AS orders, SUM(total_cents) AS revenue_cents
FROM orders
GROUP BY city
ORDER BY city;
cityordersrevenue_cents
Berlin1900
London26000
Paris24800
Sort  (cost=33.82..34.32 rows=200 width=48)
  Sort Key: city
  ->  HashAggregate  (cost=24.18..26.18 rows=200 width=48)
        Group Key: city
        ->  Seq Scan on orders  (cost=0.00..18.10 rows=810 width=36)

Filter groups

HAVING filters grouped rows after the aggregate has been computed.

SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
HAVING COUNT(*) > 1
ORDER BY status;
statusorders
paid3
Sort  (cost=26.68..26.85 rows=67 width=40)
  Sort Key: status
  ->  HashAggregate  (cost=22.15..24.65 rows=67 width=40)
        Group Key: status
        Filter: (count(*) > 1)
        ->  Seq Scan on orders  (cost=0.00..18.10 rows=810 width=32)

Try Yourself

Loaded Database:aggregation-intro.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Count only the orders whose status is paid.
2.Group orders by status and return the total revenue for each status.

What We Learned

  • COUNTcounts rows or non-NULL values.
  • SUMadds numeric values across a group.
  • GROUP BYcreates one aggregate result per distinct grouping key.
  • HAVINGfilters groups after aggregation.