0

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?

2
  • Have you tried: 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 ? Commented Jun 16, 2015 at 20:02
  • Great! This seems to speed things up on my data :) You can also post as an answer and I can give you the points Commented Jun 17, 2015 at 8:55

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.