如何看懂Postgres的执行计划
test=# insert into test select id from (select generate_series(1,10000000))ids(id);
INSERT 0 10000000
Time: 39656.016 ms
test=# select * from test where id=1;
id
----
1
(1 row)
Time: 922.950 ms
test=# explain select * from test where id=1;
QUERY PLAN
-------------------------------------------------------------
Seq Scan on test (cost=0.00..185288.50 rows=56416 width=4)
Filter: (id = 1)
(2 rows)
Time: 5633.156 ms
test=# create index idx_test on test(id);
CREATE INDEX
Time: 24070.007 ms
test=# analyze verbose test;
INFO: analyzing "public.test"
INFO: "test": scanned 30000 of 44248 pages, containing 6779952 live rows and 0 dead rows; 30000 rows in sample, 9999995 estimated total rows
ANALYZE
Time: 498.612 ms
test=# select * from test where id=100;
id
-----
100
(1 row)
Time: 3.740 ms
test=# explain select * from test where id=100;
QUERY PLAN
--------------------------------------------------------------------------
Index Only Scan using idx_test on test (cost=0.43..8.45 rows=1 width=4)
Index Cond: (id = 100)
(2 rows)
Time: 1.091 ms
cost=说明:
第一个数字0.43表示启动cost,这是执行到返回第一行时需要的cost值。
第二个数字8.45表示执行整个SQL的cost
表顺序扫描由于是立即可以获得第一行,所以启动时间一般都是0,而如果是排序操作,则需要处理完所有行后才能返回第一行,所以排序操作是需要启动时间的,下表列出了哪些操作是需要启动时间的,哪些操作不是需要的:
执行计划运算类型 操作说明 是否有启动时间
Seq Scan 扫描表 无启动时间
Index Scan 索引扫描 无启动时间
Bitmap Index Scan 索引扫描 有启动时间
Bitmap Heap Scan 索引扫描 有启动时间
Subquery Scan 子查询 无启动时间
Tid Scan ctid = …条件 无启动时间
Function Scan 函数扫描 无启动时间
Nested Loop 循环结合 无启动时间
Merge Join 合并结合 有启动时间
Hash Join 哈希结合 有启动时间
Sort 排序,ORDER BY操作 有启动时间
Hash 哈希运算 有启动时间
Result 函数扫描,和具体的表无关 无启动时间
Unique DISTINCT,UNION操作 有启动时间
Limit LIMIT,OFFSET操作 有启动时间
Aggregate count, sum,avg, stddev集约函数 有启动时间
Group GROUP BY分组操作 有启动时间
Append UNION操作 无启动时间
Materialize 子查询 有启动时间
SetOp INTERCECT,EXCEPT 有启动时间
可以explain后加analyze来通过真实执行这个SQL来获得真实的执行计划和执行时间:.
test=# explain analyze select * from test where id=100;
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------
Index Only Scan using idx_test on test (cost=0.43..8.45 rows=1 width=4) (actual time=0.021..0.021 rows=1 loops=1)
Index Cond: (id = 100)
Heap Fetches: 1
Planning time: 0.806 ms
Execution time: 0.769 ms
(5 rows)
如何看懂Postgres的执行计划
最新推荐文章于 2024-09-03 08:39:29 发布