239

I'm having a table like this

Movie Actor
A 1
A 2
A 3
B 4

I want to get the name of a movie and all actors in that movie, and I want the result to be in a format like this:

Movie ActorList
A 1, 2, 3

How can I do it?

1

2 Answers 2

418

Simpler with the aggregate function string_agg() (Postgres 9.0 or later):

SELECT movie, string_agg(actor, ', ') AS actor_list
FROM   tbl
GROUP  BY 1;

The 1 in GROUP BY 1 is a positional reference and a shortcut for GROUP BY movie in this case.

string_agg() expects data type text as input. Other types need to be cast explicitly (actor::text) - unless an implicit cast to text is defined - which is the case for all other string types (varchar, character, name, ...) and some other types.

As isapir commented, you can add an ORDER BY clause in the aggregate call to get a sorted list - should you need that. Like:

SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM   tbl
GROUP  BY 1;

But it's typically faster to sort rows in a subquery. See:

11
  • 6
    I didn't know Postgres supported positional column references like that, and can't think of any good reason to use them, but otherwise this is spot on.
    – IMSoP
    Commented Apr 6, 2013 at 11:51
  • 1
    @IMSoP: It's just a syntactical convenience I slipped in. A good use case would be a complex expressions in the SELECT list or with dynamic SQL. Commented Apr 6, 2013 at 11:54
  • 2
    Small note - might need to actor::TEXT if actor is an INT. At least, I get an error trying to string_agg INTs in Postgres 9.5 - but otherwise, this was exactly what I needed, thanks!
    – dwanderson
    Commented Dec 13, 2016 at 16:26
  • 1
    @Chris: Probably an issue with your client settings, unrelated to the query. Consider: stackoverflow.com/a/23568429/939860 Commented Jun 2, 2017 at 21:17
  • 4
    Worth noting that an optional ORDER BY clause can go into the string_agg function after the delimiter argument, e.g. string_agg(actor, ', ' ORDER BY actor DESC)
    – isapir
    Commented Oct 23, 2017 at 20:58
94

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

2
  • what is the difference between string~agg and array-agg?
    – mercury
    Commented Nov 4, 2021 at 16:55
  • 2
    @mercury, string-agg makes field with string type, that is where all elements of string_agg's argument is concatenated into single string, array-agg makes field with type array of, e.g., strings, that is where all elements of array_agg's argument will be of its original type.
    – Thatislove
    Commented Oct 15, 2022 at 10:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.