I am having trouble with my date index when my condition is either before or after a given date. Using operators (<, <=, >, >=).
My table looks like this
CREATE TABLE date_playground
(
id BIGSERIAL NOT NULL,
due_date date NOT NULL,
primary key (id)
);
And my index is
CREATE INDEX date_playground_idx_due_date
ON date_playground (due_date);
When my query is
-- SAMPLE 1
EXPLAIN ANALYZE SELECT
*
FROM date_playground
WHERE due_date = '2019-09-07' :: DATE;
This uses the index
QUERY PLAN
Index Scan using date_playground_idx_due_date on date_playground (cost=0.42..279.73 rows=75 width=287) (actual time=0.043..0.071 rows=10 loops=1)
Index Cond: (due_date = '2019-09-07'::date)
Planning Time: 0.636 ms
Execution Time: 0.140 ms
However when I use the stated operators - <, <=, >, >=
-- SAMPLE 2
EXPLAIN ANALYZE SELECT
*
FROM ln.amortization_schedule_active a
WHERE due_date <= '2019-09-07' :: DATE;
QUERY PLAN
Seq Scan on date_playground (cost=0.00..35133.86 rows=396944 width=287) (actual time=0.032..443.417 rows=404839 loops=1)
Filter: (due_date <= '2019-09-07'::date)
Rows Removed by Filter: 331870
Planning Time: 0.437 ms
Execution Time: 483.891 ms
It never uses the index, it always performs a full scan.
Can anyone suggest how can I optimize the second query?
Thanks!