在大表查询时,为充分利用服务器资源,可以尝试开启并行,多进程并发查询,提升查询效率。在执行计划中,算子前增加关键字Partial,同时有关键字 Workers Planned: xx,表示SQL使用了并行。
例如下面的SQL,未开启并行。
teledb=# explain select count(1) from teledb_1;
QUERY PLAN
---------------------------------------------------------------------------------------
Finalize Aggregate (cost=118.81..118.83 rows=1 width=8)
-> Remote Subquery Scan on all (dn001,dn002) (cost=118.80..118.81 rows=1 width=0)
-> Partial Aggregate (cost=18.80..18.81 rows=1 width=8)
-> Seq Scan on teledb_1 (cost=0.00..18.80 rows=880 width=0)
(4 rows)
下面是开启并行查询后的执行计划。
teledb=# explain select count(1) from teledb_1;
QUERY PLAN
----------------------------------------------------------------------------------------------------
Parallel Finalize Aggregate (cost=14728.45..14728.46 rows=1 width=8)
-> Parallel Remote Subquery Scan on all (dn001,dn002) (cost=14728.33..14728.45 rows=1 width=0)
-> Gather (cost=14628.33..14628.44 rows=1 width=8)
Workers Planned: 2
-> Partial Aggregate (cost=13628.33..13628.34 rows=1 width=8)
-> Parallel Seq Scan on teledb_1 (cost=0.00..12586.67 rows=416667 width=0)
(6 rows)
建议不要全局开启并行,仅在需要开启并行的具体SQL上开启,可通过会话级设置并行,或hint方式指定并行。
会话级设置如:
set max_parallel_workers_per_gather=2;
执行SQL;
set max_parallel_workers_per_gather=0;