1

I have this array:

ARRAY['this', 'is', 'my', 'string']

I would like to convert it into a string like this:

'this', 'is', 'my', 'string'

I tried:

array_to_string(ARRAY['this', 'is', 'my', 'string'], ',')

But instead of the desired output, I get this:

this, is, my, string
1
  • I wouldn't recommend using single quote characters for CSV format. Use double quotes or none. tools.ietf.org/html/rfc4180 Commented Jun 16, 2018 at 19:40

2 Answers 2

3

Unnest the array, modify (add quotes to) all its elements and aggregate them into a string:

select string_agg(format('%L', elem), ',')
-- or
-- select string_agg(quote_literal(elem), ',')
from unnest(array['this', 'is', 'my', 'string']) elem

        string_agg         
---------------------------
 'this','is','my','string'
(1 row) 
Sign up to request clarification or add additional context in comments.

4 Comments

This is a proper answer.
maybe using quote_literal function instead format can be better - or the placeholder %L for format function can be used.
@PavelStehule - I aggree, the variant with quote_literal() is probably more elegant, thanks.
It gets a list with single quoted data and coma like 'a','b'.....
0

You'll have to wrap the items of the array in single quotes yourself using character escaping, or by pre-processing the array to wrap the items in single quotes. Try this

array_to_string(ARRAY['''this''','''is''','''my''','''string'''], ',')

3 Comments

(1) Standard SQL escapes single quotes by doubling them, not with backslashes. (2) Standard SQL's string concatenation operator is ||. So I think you meant to say '''' || array_to_string(ARRAY['this', 'is', 'my', 'string'], ''', ''') || ''''.
@muistooshort is correct. If you change \' to '' everywhere in your query, you will have a good solution.
I was trying to use PostgreSQL's escaping, but I did it wrong. Standard SQL escaping ends up nicer anyway, so I've switched it as you requested.

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.