Concatenating row fields in PostgreSQL

September 18, 2007 at 11:24

Filed under: Computing — Pistos @ 11:24

If you want to concatenate multiple row results into one string, use this:

SELECT array_to_string(
  array(
    SELECT text_column
    FROM some_table
    WHERE foo = 'bar'
  ),
  ', '
);

To concatenate multiple columns for each row, use the normal text concatenation operator, ||.

SELECT array_to_string(
  array(
    SELECT text_column || '; ' || another_column
    FROM some_table
    WHERE id = 123
  ),
  ', '
);

Example

db=> SELECT * FROM users;
 firstname | lastname
-----------+----------
 John      | Doe
 Jane      | Doe
 Joe       | Bloe
(3 rows)
db=> SELECT array_to_string(
  array(
    SELECT lastname || ', ' || firstname
    FROM users
  ),
  '; '
);
         array_to_string
---------------------------------
 Doe, John; Doe, Jane; Bloe, Joe
Share This

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You may use Markdown syntax in your comment.

Powered by WP Hashcash

Powered by WordPress.
Close
E-mail It
Socialized through Gregarious 42