I am interested in how does Postgres implement the CUBE-, ROLLUP- and GROUPING SETS operators?
The implementation is based on processing sorted data. You can see result of EXPLAIN statement:
postgres=# EXPLAIN SELECT a, b, sum(c) FROM foo GROUP BY ROLLUP(a,b);
┌────────────────────────────────────────────────────────────────────┐
│ QUERY PLAN │
╞════════════════════════════════════════════════════════════════════╡
│ GroupAggregate (cost=142.54..166.99 rows=405 width=12) │
│ Group Key: a, b │
│ Group Key: a │
│ Group Key: () │
│ -> Sort (cost=142.54..147.64 rows=2040 width=12) │
│ Sort Key: a, b │
│ -> Seq Scan on foo (cost=0.00..30.40 rows=2040 width=12) │
└────────────────────────────────────────────────────────────────────┘
(7 rows)
postgres=# EXPLAIN SELECT a, b, sum(c) FROM foo GROUP BY CUBE(a,b);
┌────────────────────────────────────────────────────────────────────┐
│ QUERY PLAN │
╞════════════════════════════════════════════════════════════════════╡
│ GroupAggregate (cost=142.54..302.48 rows=605 width=12) │
│ Group Key: a, b │
│ Group Key: a │
│ Group Key: () │
│ Sort Key: b │
│ Group Key: b │
│ -> Sort (cost=142.54..147.64 rows=2040 width=12) │
│ Sort Key: a, b │
│ -> Seq Scan on foo (cost=0.00..30.40 rows=2040 width=12) │
└────────────────────────────────────────────────────────────────────┘
(9 rows)
Data are sorted, and then continually aggregated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With