Is it possible to limit the number of elements in the following string_agg
function?
string_agg(distinct(tag),', ')
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 ,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With