pg_hint_plan概述
pg_hint_plan是一个革命性的PostgreSQL扩展,它赋予了开发者手动干预查询执行计划的能力。你可以指定表的访问方式、连接顺序、连接方式、并行查询...只要你看执行计划不爽,你就拍优化器的脑袋。
pg_hint_plan架构

pg_hint_plan安装
1、下载(与数据库对应的版本)
https://github.com/ossc-db/pg_hint_plan/releases
2、解压并部署文件
make clean
make
make install
3、安装并部署
postgres=# create extension pg_hint_plan;
4、修改配置文件postgresql.conf
shared_preload_libraries = 'pg_hint_plan'
pg_hint_plan.enable_hint = on
pg_hint_plan.debug_print = on
pg_hint_plan.message_level = log
pg_hint_plan应用
• 扫描方法提示
表、表函数、常量值语句、通用表达式、视图和子查询无效。
explain /*+ IndexScan(t1 t1_id_ind) */ select * from table1 t1 where id=100;
• 连接方式提示
连接方法提示强制指定相关表连接的方法。对普通表、继承表、无日志表、临时表、外部表、系统表、表函数、常量值命令和通用表达式有效。对视图和子查询无效。
explain /*+
NestLoop(t1 t2)
*/
SELECT * FROM table1 t1
JOIN table2 t2 ON (t1.key = t2.key);
• 连接顺序提示
Leading提示强制两个或多个表的连接顺序。
explain /*+
Leading(t3 t2 t1)
*/
SELECT * FROM table1 t1
JOIN table2 t2 ON (t1.key = t2.key)
JOIN table3 t3 ON (t2.key = t3.key);
• 并行执行提示
Parallel提示强制扫描的并行执行配置。第三个参数指定强制强度:soft 表示仅修改 max_parallel_worker_per_gather,其他参数由规划器决定;hard 强制修改其他规划器参数。该提示作用于普通表、分区表父表、UNLOGGED表和系统表。外部表、表函数、VALUES 子句、CTE、视图和子查询无效。视图的内部表可通过真实名称或别名指定。
EXPLAIN /*+
Parallel(t1 3 hard)
Parallel(t2 5 hard)
*/
SELECT * FROM table1 t1
JOIN table2 t2 ON (t1.key = t2.key);
• GUC参数配置提示
Set提示在查询规划期间临时修改GUC参数。只要不与其他规划方法配置参数冲突,查询规划中的GUC参数可以影响规划。当多个提示修改同一GUC时,最后一个生效。pg_hint_plan的GUC参数也可通过此提示设置,但可能不会生效。
Explain
/*+ Set(random_page_cost 2.0) */
SELECT * FROM table1 t1 WHERE key = 'value';
• 行数校正提示
行数校正提示会校正由查询优化器导致的行数错误。
/*+ Rows(a b #10) */ SELECT... ; 设置连接结果的行数为10
/*+ Rows(a b +10) */ SELECT... ; 行数增加10
/*+ Rows(a b -10) */ SELECT... ; 行数减去10
/*+ Rows(a b *10) */ SELECT... ; 行数增大10倍
explain /*+ Rows(t1 t2 *2) */ SELECT * FROM table1 t1 JOIN table2 t2 ON (t1.key = t2.key);
explain /*+ Rows(t1 t2 *10) */ SELECT * FROM table1 t1 JOIN table2 t2 ON (t1.key = t2.key);
PostgreSQL中文社区认证
与工信部人才交流中心合作,推出PostgreSQL初/中/高级证书,证书中明确指定适用于信息技术应用创新人才岗位能力评定要求。

