官术网_书友最值得收藏!

Investigating performance

Grouping sets is a powerful feature; they help to reduce the number of expensive queries. Internally, PostgreSQL will basically use MixedAggregate to perform the aggregation. It can perform many operations at once, which ensures efficiency, as shown in the following example:

test=# explain SELECT region, country, avg(production) 
FROM t_oil
WHERE country IN ('USA', 'Canada', 'Iran', 'Oman')
GROUP BY GROUPING SETS ( (), region, country);
QUERY PLAN
--------------------------------------------------------------------
MixedAggregate (cost=0.00..18.17 rows=17 width=52)
Hash Key: region
Hash Key: country
Group Key: ()
-> Seq Scan on t_oil (cost=0.00..15.66 rows=184 width=24)
Filter: (country = ANY ('{USA,Canada,Iran,Oman}'::text[]))
(6 rows)

In older versions of PostgreSQL, the system used GroupAggregate to perform this operation in all cases. In a more modern version, MixedAggregate has been added. However, you can still force the optimizer to use the old strategy using the enable_hashagg setting. MixedAggregate is essentially HashAggregate and therefore the same setting applies, as shown in the next example:

test=# SET enable_hashagg TO off;
SET
test=# explain SELECT region, country, avg(production)
FROM t_oil
WHERE country IN ('USA', 'Canada', 'Iran', 'Oman')
GROUP BY GROUPING SETS ( (), region, country);
QUERY PLAN
--------------------------------------------------------------------------
GroupAggregate (cost=22.58..32.48 rows=17 width=52)
Group Key: region
Group Key: ()
Sort Key: country
Group Key: country
-> Sort (cost=22.58..23.04 rows=184 width=24)
Sort Key: region
-> Seq Scan on t_oil (cost=0.00..15.66 rows=184 width=24)
Filter: (country = ANY ('{USA,Canada,Iran,Oman}'::text[]))
(9 rows)
test=# SET enable_hashagg TO on;
SET

In general, the hash-based version (MixedAggregate) is faster and is favored by the optimizer if there is enough memory to keep the hash needed for MixedAggregate in memory.

主站蜘蛛池模板: 新竹县| 错那县| 谷城县| 辰溪县| 宁武县| 祁东县| 麦盖提县| 宜春市| 潮安县| 香河县| 蒙山县| 澎湖县| 象山县| 贵港市| 荥阳市| 剑川县| 施甸县| 通化县| 东城区| 左贡县| 九寨沟县| 丽水市| 余干县| 平顺县| 廉江市| 阿拉尔市| 阆中市| 蒙阴县| 神木县| 介休市| 攀枝花市| 南开区| 四平市| 景德镇市| 隆回县| 五华县| 吕梁市| 论坛| 乐平市| 湖州市| 平湖市|