os: centos 7.4.1708
db: postgresql 11.9
版本
# cat /etc/centos-release
CentOS Linux release 7.4.1708 (Core)
# su - postgres
$ psql -c "select version();"
version
---------------------------------------------------------------------------------------------------------
PostgreSQL 11.9 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
(1 row)
explain
peiybdb=# create table tmp_t0(
id bigserial,
name varchar(100),
memo varchar(100)
);
peiybdb=# insert into tmp_t0(name,memo)
select md5(id::varchar),md5(md5(id::varchar))
from generate_series(1,10000) as id;
peiybdb=# vacuum analyze tmp_t0;
peiybdb=# explain select * from tmp_t0 limit 10;
QUERY PLAN
-------------------------------------------------------------------
Limit (cost=0.00..0.23 rows=10 width=74)
-> Seq Scan on tmp_t0 (cost=0.00..234.00 rows=10000 width=74)
(2 rows)
peiybdb=# explain analyze select * from tmp_t0 limit 10;
QUERY PLAN
--------------------------------------------------------------------------------------------------------------
Limit (cost=0.00..0.23 rows=10 width=74) (actual time=0.011..0.015 rows=10 loops=1)
-> Seq Scan on tmp_t0 (cost=0.00..234.00 rows=10000 width=74) (actual time=0.010..0.011 rows=10 loops=1)
Planning Time: 0.044 ms
Execution Time: 0.032 ms
(4 rows)
cost=0.00…234.00
第一个数字 0.00 表示启动的成本,返回第一行需要多少 cost 值。
第二个数字 234.00 表示返回所有数据的成本。
cost 基于如下的一些规则计算出的数字(默认):
顺序扫描一个块,cost的值为 1
随机扫描一个块,cost的值为 4
处理一个数据行的CPU代价,cost的值为 0.01
处理一个索引行的CPU代价,cost的值为 0.005
每个操作的CPU代价为 0.0025
peiybdb=# select name,setting,unit
from pg_settings ps
where name in (
'seq_page_cost',
'random_page_cost',
'cpu_tuple_cost',
'cpu_index_tuple_cost',
'cpu_operator_cost'
);
name | setting | unit
----------------------+---------+------
cpu_index_tuple_cost | 0.005 |
cpu_operator_cost | 0.0025 |
cpu_tuple_cost | 0.01 |
random_page_cost | 4 |
seq_page_cost | 1 |
(5 rows)
rows=10000
表示会返回 10000行。
width=74
表示每行平均宽度为74字节。