Supposing I have this table with index.
Create Table sample
(
table_date timestamp without timezone,
description
);
CREATE INDEX dailyinv_index
ON sample
USING btree
(date(table_date));
And It has a 33 million rows.
Why is it that running this query
select count(*) from sample where date(table_date) = '8/30/2017' and desc = 'desc1'
yields a result @ 12ms
Using PostgreSQL to explain the query plan. this is what it does.
Aggregate (cost=288678.55..288678.56 rows=1 width=0)
->Bitmap Heap Scan on sample (cost=3119.63..288647.57 rows=12393 width=0)
Recheck Cond: (date(table_date) = '2017-08-30'::date)
Filter: ((description)::text = 'desc1'::text)
-> Bitmap Index Scan on dailyinv_index (cost=0.00..3116.54 rows=168529 width=0)
Index Cond: (date(table_date) = '2017-08-30'::date)
but this one
select date(table_date) from sample where date(table_date)<='8/30/2017' order by table_date desc limit 1
yields result after 11,460 ms?
Query Plan
Limit (cost=798243.52..798243.52 rows=1 width=8)
-> Sort (cost=798243.52..826331.69 rows=11235271 width=8)
Sort Key: table_date
-> Bitmap Heap Scan on sample (cost=210305.92..742067.16 rows=11235271 width=8)
Recheck Cond: (date(table_date) <= '2017-08-30'::date)
-> Bitmap Index Scan on dailyinv_index (cost=0.00..207497.10 rows=11235271 width=0)
Index Cond: (date(table_date) <= '2017-08-30'::date)
PostgreSQL Version: 9.4
Maybe Im doing the indexing wrong or I dont know. Really not familiar with indexing. Any help would be great. Thanks a lot!
Your problem is caused by you sorting on table_date
rather than date(table_date)
. This can be corrected by modyfing the query to:
SELECT DATE(table_date)
FROM sample
WHERE DATE(table_date) <= '8/30/2017'
ORDER BY DATE(table_date) DESC
LIMIT 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.