Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

sql - Why postgres is not using the index in my query

I have 2 tables as follow:

tb_st:
Columns:
st_id  | integer
st     | character varying(80)
type   | integer
Indexes:
    PRIMARY KEY (st_id)
    UNIQUE INDEX (st, type)
    INDEX (st)

tb_pd:
Column
st_id  | integer
bot_id | integer
Indexes:
    PRIMARY KEY (st_id, bot_id)
    INDEX (bot_id)
Foreign-key constraints:
    FOREIGN KEY (st_id) REFERENCES tb_st(st_id)

When i explain the query:

select p.bot_id
from tb_pd p inner join
     tb_st s
     on p.st_id = s.st_id
where s.st = 'abc' and s.type = 1

postgres gives me this:

 Nested Loop  (cost=4.24..16.10 rows=11 width=194)
   ->  Seq Scan on tb_st s  (cost=0.00..1.07 rows=1 width=186)
         Filter: (((st)::text = 'abc'::text) AND (type = 1))
   ->  Bitmap Heap Scan on tb_pd p  (cost=4.24..14.91 rows=11 width=8)
         Recheck Cond: (st_id = s.st_id)
         ->  Bitmap Index Scan on tb_pd_pkey  (cost=0.00..4.24 rows=11 width=0)
               Index Cond: (st_id = s.st_id)
(7 rows)

after a while gave me this for the exact same query (still not using indexes):

 Nested Loop  (cost=0.00..2.19 rows=1 width=4)
   Join Filter: (p.st_id = s.st_id)
   ->  Seq Scan on tb_st s  (cost=0.00..1.07 rows=1 width=4)
         Filter: (((st)::text = 'abc'::text) AND (type = 1))
   ->  Seq Scan on tb_pd p  (cost=0.00..1.05 rows=5 width=8)
(5 rows)

My question is: If i am only filtering by a st value and a type value that composes a UNIQUE INDEX, why this unique index is not being used?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your tables don't have enough rows to use an index. They fit in a single disk page, so it's faster to read the entire thing and filter rows out using cpu time than it is to do the same thing twice (once for the index, and another time for the data).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...