Given a table with around 5 million records added per month, this simple query has vastly different run times from the first execution to the 2nd:
select count(*) from my_table where recorded_at > '2018-01-24 23:59:59'
- First execution: count = 8,756,237 execution time = ~5 minutes
- Second execution: count = 8,756,237 execution time = ~3 seconds
There is an index on the field recorded_at.
CREATE INDEX my_table__recorded_at ON my_table(recorded_at);
Does this difference in execution time indicate that the index is not being updated correctly?
Its the same for other dates:
select count(*) from my_table where recorded_at > '2018-02-07 23:59:59'
- First execution: count = 6,487,274 execution time = ~4 minutes
- Second execution: count = 6,487,274 execution time = ~3 seconds
This is running on AWS Aurora postgres with an r4.xlarge instance
EXPLAIN SELECT count(*) FROM my_table WHERE recorded_at > '2018-02-07 23:59:59';That said, I strongly suspect what you're seeing is the effect of caching the table and/or index. First time it runs, it reads everything in and caches things. Second time, it just has to go to the cache. Finally, unless Aurora is wildly different from postgres proper, indexes always get updated.