Reputation: 41919
I have a books table in a postgres database that has a user_id column. When there was no index, querying all the books with a certain user_id took 0.607 ms
lesson4=# select * from books where user_id = 5;
Time: 0.607 ms
I then created an index like this
lesson4=# create index user_idx on books (user_id);
CREATE INDEX
Time: 43.288 ms
I then ran the same query and it took more than double the time
lesson4=# select * from books where user_id = 5;
Time: 1.397 ms
Note, there are only a few rows in the database. Not sure if that has an impact.
Did I create the index correctly? Why is it running slower now?
Upvotes: 0
Views: 2362
Reputation: 26454
Your query is a little over three times as slow. Here's what is probably happening, assuming:
The planner determines the index might help, so it does an index scan. This requires a tree search through the index, followed by a sequential scan through the relevant pages.
Without the index, you do a sequential scan through the ten pages, find the answer. Not only is the second faster, it is simpler.
This is why on PostgreSQL, indexes aren't the magic answer for performance problems. Usually it is worth noting that performance is approaching the danger zone before even thinking about adding an index.
Upvotes: 1