对PostgreSQL的执行计划的初步学习
开始
table 的状况:
[作者:技术者高健@博客园 mail: luckyjackgao@gmail.com ]
postgres=# analyze gaotab; ANALYZE postgres=# select a.relpages, a.reltuples, a.relfilenode,a.reltype,b.typname from pg_class a, pg_type b where a.relname like 'gaotab%' and a.reltype=b.oid; relpages | reltuples | relfilenode | reltype | typname ----------+-----------+-------------+---------+--------- 1 | 100 | 16387 | 16386 | gaotab (1 row)
成本参数:
postgres=# show seq_page_cost; seq_page_cost --------------- 1 (1 row) postgres=# show cpu_tuple_cost; cpu_tuple_cost ---------------- 0.01 (1 row)
postgres=# show cpu_operator_cost; cpu_operator_cost ------------------- 0.0025 (1 row)
查询的代价:
postgres=# explain select * from gaotab; QUERY PLAN --------------------------------------------------------- Seq Scan on gaotab (cost=0.00..2.00 rows=100 width=17) (1 row) postgres=#
这么一个普通的查询所有记录的语句,具体执行的时候,首先要读取磁盘页面,然后是把每一条记录取出来。没有多余的运算。
所以,其计划类型为 Seq Scan,而其代价为:
relpages * seq_page_cost + reltuples * cpu_tuple_cost =1×1 + 100×0.01=2
再来:
postgres=# explain select * from gaotab where id=15; QUERY PLAN ------------------------------------------------------- Seq Scan on gaotab (cost=0.00..2.25 rows=1 width=17) Filter: (id = 15) (2 rows)
此时,由于有了一个 判断 id=15 的运算,成本还要高一些,此时用到了 cpu_operator_cost:
relpages * seq_page_cost + reltuples * cpu_tuple_cost + reltuples* cpu_operator_cost
=1*1+100*0.01+100*0.0025=2.25
[作者:技术者高健@博客园 mail: luckyjackgao@gmail.com ]
结束