Forum

Posted by Divya, Feb. 20, 2023, 2:35 a.m.

SQL to get multiple rows value as comma separated

Answers

Which database is this? For Postgres, use string_agg() to merge multiple rows into the same row.

  1. Step 1: do an inner join of all 3 tables to get staff_id, staff_name and roles;
  2. Step 2: collapse the roles column with string_agg or something similar and group by the first 2 columns.
SQLPad user avatar

Kerry (53)

Feb. 20, 2023, 11:23 a.m.

Depending on which SQL flavor you're using, STRING_AGG or GROUP_CONCAT is definitely the way to go for this. I usually run a quick check on the output to make sure the delimiters didn't get messed up by null values. I’ve been using this https://www.thetoolapp.com/comma-seperator-online/ to double-check my lists or reformat them quickly after exporting the query results. It saves a lot of manual cleanup!

SQLPad user avatar

Pitter (2)

April 23, 2026, 3:43 a.m.