Speed up Min/Max operation on postgres with index for IN operator query

740 views Asked by At

I would like to optimize the following query in postgres

SELECT(MIN("products"."shipping") AS minimal FROM "products" WHERE "products"."tag_id" IN (?)

with an index like

CREATE INDEX my_index ON products (tag_id, shipping DESC);

Unfortunately this one is only used when it's just one tag. Almost alwayst it is queried for a handful of tags at the same time, but then postgres uses the index products (shipping DESC) which is quite slow. What could I do to speed up my query?

1

There are 1 answers

0
krokodilko On BEST ANSWER

It turned out (please see comments), that this query:

SELECT MIN(minimal) AS minimal 
FROM ( 
  SELECT  MIN("products"."shipping") AS minimal 
  FROM "products" 
  WHERE "products"."tag_id" IN (?,?,?,?,?,?,?) 
  GROUP BY "tag_id" 
) some_alias

is able to deceive PostgreSQL in such a way, that it performs better because, as I guess, it uses the index in this case.