I have table in postgres database. After the row reach 2 mio rows, the query become slower. This is my query
SELECT
c.source,
c.destination,
c.product_id,
sum(c.weight),
count(c.weight),
c.owner_id
FROM stock c
GROUP BY c.source, c.destination, c.product_id, c.owner_id;
I already add index
CREATE INDEX stock_custom_idx ON public.stock USING btree (source, destination, product_id, owner_id)
The query is very slow, so I do explain analyze, but the index not called.
So, how to optimize this query, because its take too long time and not return data?
EXPLAINafter adding this index and not at some other point?EXPLAIN? Note that for fairly small table sizes, Postgres may choose to not use the index. The big issue here would be if you have a very large table plus the index, but Postgres is still choosing not to use that index.explain (analyze, buffers, format text)(not just a "simple" explain) as formatted text and make sure you preserve the indention of the plan. Paste the text, then put```on the line before the plan and on a line after the plan. Please also include completecreate indexstatements for all indexes as well.