使用索引提高查询效率 本页介绍天翼云TeleDB数据库使用索引提高查询效率的最佳实践。 通过explain查看执行计划,查看SQL语句是否使用到了索引,Seq Scan表示对表进行了全表扫描,而如Index Scan,Index Only Scan则表示使用了索引扫描。 通常情况下,使用索引可以加速查询速度,但索引也会增加数据更新的开销,在数据量较小时,优化器也可能会使用全表扫描代替索引扫描。 例如,下面的SQL语句,使用了Parallel Seq Scan并行全表扫描。 teledb explain select from teledb2 where f3'1'; QUERY PLAN Remote Fast Query Execution (cost0.00..0.00 rows0 width0) Node/s: dn001, dn002 > Gather (cost1000.00..7827.20 rows1 width14) Workers Planned: 2 > Parallel Seq Scan on teledb2 (cost0.00..6827.10 rows1 width14) Filter: (f3 '1'::text) (6 rows) 在f2字段上创建索引后,下面的SQL语句,使用了Index Scan索引扫描。 teledb create index teledb2f2idx on teledb2(f2); CREATE INDEX postgres explain select from teledb2 where f21; QUERY PLAN Remote Fast Query Execution (cost0.00..0.00 rows0 width0) Node/s: dn001, dn002 > Index Scan using teledb2f2idx on teledb2 (cost0.42..4.44 rows1 width14) Index Cond: (f2 1) (4 rows) 当然,按SQL优化原则,上述SQL语句where条件都没有带分布键,导致SQL下发到了所有DN节点,建议尝试优化为带分布键查询。