[FIXED] Postgresql put strings inside quotes with array_to_string

Issue

In select I have used array_to_string like this (example)

array_to_string(array_agg(tag_name),';') tag_names

I got resulting string "tag1;tag2;tag3;..." but I would like to get resulting string as "'tag1';'tag2';'tag3';...".

How can I do this in Postgres?


Solution

Use the functions string_agg() and format() with the %L placeholder, which quotes the argument value as an SQL literal.

with my_table(tag_name) as (
values 
    ('tag1'),
    ('tag2'),
    ('tag3')
)

select string_agg(format('%L', tag_name), ';' order by tag_name) tag_names
from my_table;

      tag_names       
----------------------
 'tag1';'tag2';'tag3'
(1 row)

Alternatively, format('%L', tag_name) may be replaced with quote_nullable(tag_name).



Answered By - klin
Answer Checked By - Robin (sql.easybugfix Admin)

Related Posts

Post a Comment