Reputation: 254
I am doing, in postgresql, something like this:
select A.first,
count(B.second) as count,
array_agg(A.second) as second,
array_agg(A.third) as third,
array_agg(B.kids) as kids
from A join B on A.first=B.second
group by A.first;
And it's taking forever (also because the tables are pretty big). Limiting the output to 10 row and looking with explain analyze told me there's a nested loop which is huge and takes most of the time.
Is there any way in which I can write this query (which I'll then use in CREATE TABLE AS to create a new table) to speed it up, while conserving the same output, which is what I want?
Thanks!
Upvotes: 1
Views: 96
Reputation: 425318
Ensure the column bring used as a foreign key is indexed:
create index b_second on b(second);
Without such an index, every row of a
would cause a table scan of b
, which would make your query crawl.
Upvotes: 1