In my postgreSQL database I have a table named "product". In this table I have a column named "date_touched" with type timestamp. I created a simple btree index on this column. This is the schema of my table (I omitted irrelevant column & index definitions):
Table "public.product" Column | Type | Modifiers ---------------------------+--------------------------+------------------- id | integer | not null default nextval('product_id_seq'::regclass) date_touched | timestamp with time zone | not null Indexes: "product_pkey" PRIMARY KEY, btree (id) "product_date_touched_59b16cfb121e9f06_uniq" btree (date_touched) The table has ~300,000 rows and I want to get the n-th element from the table ordered by "date_touched". when I want to get the 1000th element, it takes 0.2s, but when I want to get the 100,000th element, it takes about 6s. My question is, why does it take too much time to retrieve the 100,000th element, although I've defined a btree index?
Here is my query with explain analyze that shows postgreSQL does not use the btree index and instead sorts all rows to find the 100,000th element:
- first query (100th element):
explain analyze SELECT product.id FROM product ORDER BY product.date_touched ASC LIMIT 1 OFFSET 1000; QUERY PLAN ----------------------------------------------------------------------------------------------------- Limit (cost=3035.26..3038.29 rows=1 width=12) (actual time=160.208..160.209 rows=1 loops=1) -> Index Scan using product_date_touched_59b16cfb121e9f06_uniq on product (cost=0.42..1000880.59 rows=329797 width=12) (actual time=16.651..159.766 rows=1001 loops=1) Total runtime: 160.395 ms - second query (100,000th element):
explain analyze SELECT product.id FROM product ORDER BY product.date_touched ASC LIMIT 1 OFFSET 100000; QUERY PLAN ------------------------------------------------------------------------------------------------------ Limit (cost=106392.87..106392.88 rows=1 width=12) (actual time=6621.947..6621.950 rows=1 loops=1) -> Sort (cost=106142.87..106967.37 rows=329797 width=12) (actual time=6381.174..6568.802 rows=100001 loops=1) Sort Key: date_touched Sort Method: external merge Disk: 8376kB -> Seq Scan on product (cost=0.00..64637.97 rows=329797 width=12) (actual time=1.357..4184.115 rows=329613 loops=1) Total runtime: 6629.903 ms