I have ARRAY_AGG( distinct CAST (asset_group_id AS text))
which returns array of hundreds of elements but I want only first 100 elements.
I didn’t find any such function available in postgres array documentation.
How can I achieve it in the postgres?
2
Answers
Just use a CTE to limit to 100 elements, then create the array, like
And using window functions would be like
by the way in this case is better performant the common table expression.
PostgreSQL arrays support subscripts and slices.
In your case, to get the first 100 elements: demo
It’s better for static, existing arrays. In your case, you’re building one, collecting all your distinct elements and this discards everything past that first 100, wasting the rest of the work put into finding all other distinct values. It’s better to not collect more than you need in the first place, as Pepe N O suggested, using a
limit
in a CTE:or a plain subquery
The demo shows the performance difference between just grabbing the first distinct 100 and no more, versus having to collect all distincts and then discarding everything past the first 100.