Search code examples
mysqlpostgresqlconcatenationgroup-concat

MySQL group concat conversion to Postgres using two concatenated columns


How can I create a similar query using Postgres to recreate this MySQL version.

SELECT u.id, GROUP_CONCAT(CONCAT(r.firstname,' ',r.lastname, ' [', r.type,']') SEPARATOR ', ') AS names
FROM reference r, users u
WHERE r.user_id = u.id
GROUP BY r.user_id

Solution

  • Use string_agg. Also, use explicit join syntax.

    SELECT u.id, string_agg(r.firstname || ' ' || r.lastname || ' [' || r.type || ']' , ', ') AS names
    FROM reference r join users u
    on r.user_id = u.id
    GROUP BY r.user_id