0

I have a query as follows:

SELECT string_agg(sn::text, ','), product_id
  FROM irmsapp_serializedinventory
  group by product_id;

The result is an aggregated sno field and products. I would like to know if we can limit the concatenations to 5 and leave the rest for the sno field. Currently my sno field is a big list and i want to reduce it to a list of 5 elements(the first 5 elements in the sorted order).

2
  • the first five elements Commented Mar 19, 2015 at 4:14
  • I want them in sorted order.. Commented Mar 19, 2015 at 14:20

1 Answer 1

2

Rows in a relational database are not "sorted". You need to have some column by which you can sort the result, only then you can specify which rows are the "first five".

Assuming you have e.g. a created_at column that defines the "first five", you can do something like this:

select string_agg(sno::text, ','), product_id
from (
   select product_Id, sno,
          row_number() over (partition by product_id order by created_at desc) as rn
   from irmsapp_serializedinventory
) t
where rn <= 5
group by product_id;

This picks 5 rows per product. If you just want 5 rows regardless of the product_id then just remove the partition by product_id in the window function.

The order by created_at desc is what defines the sort order and what defines which five rows are being used in the aggregation.

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

2 Comments

hi i have a question. What if my rows are already sorted and i need to get the first 5?
@RogerFederer: again: rows in a relational database are NOT "sorted". The only (really: the only) way to guarantee a sort order is to use an order by there is no alternative.

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.