Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Postgres implement the CUBE-, ROLLUP- and GROUPING SETS operators

I am interested in how does Postgres implement the CUBE-, ROLLUP- and GROUPING SETS operators?

like image 977
Maros Mayer Avatar asked May 01 '26 13:05

Maros Mayer


1 Answers

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.

like image 128
Pavel Stehule Avatar answered May 04 '26 22:05

Pavel Stehule