作者:瀚高PG实验室 (Highgo PG Lab)-海无涯
创建一个表test,并插入一定的数据
highgo=# select * from test;
id | name | profession
------+--------+--------------
1 | TOM | accounting
1 | JERRY | accounting
2 | JERRY | accounting
2 | JUGG | Business
10 | 瀚高 | 基础软件
11 | 瀚高 | 基础软件
12 | 瀚高 | 基础软件
13 | 瀚高 | 基础软件
14 | 瀚高 | 基础软件
15 | 瀚高 | 基础软件
16 | 瀚高 | 基础软件
17 | 瀚高 | 基础软件
18 | 瀚高 | 基础软件
19 | 瀚高 | 基础软件
20 | 瀚高 | 基础软件
21 | 瀚高 | 基础软件
22 | 瀚高 | 基础软件
23 | 瀚高 | 基础软件
24 | 瀚高 | 基础软件
25 | 瀚高 | 基础软件
26 | 瀚高 | 基础软件
27 | 瀚高 | 基础软件
28 | 瀚高 | 基础软件
29 | 瀚高 | 基础软件
30 | 瀚高 | 基础软件
31 | 瀚高 | 基础软件
……
highgo=# select count(*) from test;
count
-------
1005
(1 row)
打开计时
highgo=# \timing
Timing is on.
查看效果
highgo=# explain analyze select * from test where id = '13';
QUERY PLAN
------------------------------------------------------------------------------------------------
Seq Scan on test (cost=0.00..19.56 rows=1 width=22) (actual time=0.013..0.175 rows=1 loops=1)
Filter: (id = 13)
Rows Removed by Filter: 1004
Planning time: 0.053 ms
Execution time: 0.201 ms
(5 rows)
Time: 0.685 ms
highgo=# create index idx_test_id on test(id);
CREATE INDEX
Time: 325.900 ms
highgo=# \di
List of relations
Schema | Name | Type | Owner | Table
--------+-------------+-------+--------+-------
public | idx_test_id | index | highgo | test
(1 row)
highgo=# explain analyze select * from test where id = '13';
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------
Index Scan using idx_test_id on test (cost=0.28..8.29 rows=1 width=22) (actual time=0.023..0.023 rows=1 loops=1)
Index Cond: (id = 13)
Planning time: 0.239 ms
Execution time: 0.042 ms
(4 rows)
Time: 0.322 ms
。
虽然只有一千多行的数据,但是仍然可以看出快了不少。