Skip to content
Advertisement

How can I utilize a partial index for the calculated filter condition in a where clause?

Let’s say I have this simple query:

This is a 1GB+ table with a partial index on created_at column. When I run this query it does sequential scan and does not utilise my index which obviously takes much time:

On the other hand if I’d have a “hardcoded” (or pre-calculated) value like this:

It would utilise an index on created_at:

If I could I’d just use an ORM and generate a query with the right value but I can’t. Is there a way I can maybe pre-calculate this timestamp and use it in a WHERE clause via plain SQL?


Adding a little bit of tech info of my setup.

PostgreSQL version: 9.6.11

created_at column type is: timestamp

index: "index_audiences_on_created_at" btree (created_at) WHERE created_at > '2020-10-01 00:00:00'::timestamp without time zone

Advertisement

Answer

This is not the exact answer. But can do with specific situation

As you have the predicate (created_at > '2020-10-01 00:00:00'::timestamp without time zone) , if the filtering condition is greater than the predicate condition. Then you can prepend the condition in where

Note: may be instead of TIMESTAMP , you have to put TIMESTAMP without time zone or TIMESTAMP with time zone. Depends on column type

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement