使用索引提高查詢效率
更新時間 2025-02-05 09:36:57
最近更新時間: 2025-02-05 09:36:57
分享文章
本頁介紹天翼云TeleDB數據庫使用索引提高查詢效率的最佳實踐。
通過explain查看執行計劃,查看SQL語句是否使用到了索引,Seq Scan表示對表進行了全表掃描,而如Index Scan,Index Only Scan則表示使用了索引掃描。
通常情況下,使用索引可以加速查詢速度,但索引也會增加數據更新的開銷,在數據量較小時,優化器也可能會使用全表掃描代替索引掃描。
例如,下面的SQL語句,使用了Parallel Seq Scan并行全表掃描。
teledb=# explain select * from teledb_2 where f3='1';
QUERY PLAN
--------------------------------------------------------------------------------
Remote Fast Query Execution (cost=0.00..0.00 rows=0 width=0)
Node/s: dn001, dn002
-> Gather (cost=1000.00..7827.20 rows=1 width=14)
Workers Planned: 2
-> Parallel Seq Scan on teledb_2 (cost=0.00..6827.10 rows=1 width=14)
Filter: (f3 = '1'::text)
(6 rows)
在f2字段上創建索引后,下面的SQL語句,使用了Index Scan索引掃描。
teledb=# create index teledb_2_f2_idx on teledb_2(f2);
CREATE INDEX
postgres=# explain select * from teledb_2 where f2=1;
QUERY PLAN
-------------------------------------------------------------------------------------
Remote Fast Query Execution (cost=0.00..0.00 rows=0 width=0)
Node/s: dn001, dn002
-> Index Scan using teledb_2_f2_idx on teledb_2 (cost=0.42..4.44 rows=1 width=14)
Index Cond: (f2 = 1)
(4 rows)
當然,按SQL優化原則,上述SQL語句where條件都沒有帶分布鍵,導致SQL下發到了所有DN節點,建議嘗試優化為帶分布鍵查詢。