Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate with a limit in postgres

In this query, each row of table a could have hundreds of rows of table b associated with it. So the array_agg contains all of those values. I'd like to be able to set a limit for it, but instide array_agg I can do order by but there's no way to set a limit.

select a.column1, array_agg(b.column2)
from a left join b using (id)
where a.column3 = 'value'
group by a.column1

I could use the "slice" syntax on the array but that's quite expensive since it first has to retrieve all the rows then discard the other ones. What's the proper efficient way to do this?

like image 378
user779159 Avatar asked Dec 09 '25 16:12

user779159


1 Answers

I would use a lateral join.

select a.column1, array_agg(b.column2)
from a left join lateral 
    (select id, column2 from b where b.id=a.id order by something limit 10) b using (id)
where a.column3 = 'value'
group by a.column1

Since the "id" restriction is already inside the lateral query, you could make the join condition on true rather than using (id). I don't know which is less confusing.

like image 197
jjanes Avatar answered Dec 11 '25 12:12

jjanes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!