Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - string_agg with limited number of elements

Is it possible to limit the number of elements in the following string_agg function?

 string_agg(distinct(tag),', ')
like image 834
nickbusted Avatar asked Dec 10 '14 15:12

nickbusted


1 Answers

There are two more ways.

1) make an array from rows, limit it, and then concatenate into string:

SELECT array_to_string((array_agg(DISTINCT tag))[1:3], ', ') FROM tbl

("array[1:3]" means: take items from 1 to 3 from array)

2) concatenate rows into string without limit, then use "substring" to trim it:

string_agg(distinct(tag),',')

If you know that your "tag" field cannot contain , character then you can select all text before nth occurence of your ,

SELECT substring(
string_agg(DISTINCT tag, ',')
from '(?:[^,]+,){1,3}')
FROM tbl

This substring will select 3 or less strings divided by ,

like image 75
alexkovelsky Avatar answered Sep 24 '22 16:09

alexkovelsky