I am using postgress database (Version 9.5.4), I have a table structure like this,
create table test (
id serial primary key,
company_name varchar(255) not null,
department varchar(255) not null,
joined_date timestamp not null
);
Following are my exact queries (Only the below three not any other),
-
Query 1
SELECT * FROM test WHERE joined_date::date BETWEEN '2017-09-25' AND '2017-10-25';
-
Query 2
SELECT * FROM test WHERE joined_date::date BETWEEN '2017-09-25' AND '2017-10-25' AND company_name = 'xxx';
-
Query 3
SELECT * FROM test WHERE joined_date::date BETWEEN '2017-09-25' AND '2017-10-25' AND company_name = 'xxx' AND department = 'yyy';
I want to speed up my query execution time, I tried to add index some thing like this,
CREATE INDEX index_test ON test (joined_date, company_name, department);
After creating index, the query execution time doesn't have any improvement. On adding EXPLAIN keyword, I found the index is no longer used. But when adding equals condition instead of between keyword, index is being used. But my use case would be within date range and optional fields with equal condition. How to achieve my index use case with most efficient performance?
Best Answer
Index will be used if you remove cast to date (
joined_date
instead ofjoined_date::date
) fromWHERE
clause (upper bound inBETWEEN
should be changed accordingly).Alternatively , you can create index as
CREATE INDEX index_test2 ON test (cast (joined_date as date), company_name, department);
Proof
Query 1
Query 2
Query 3