Forum

Convert Rows to Com...
 
Share:
Notifications
Clear all

Convert Rows to Comma-Separated Values in SQL — Simple Methods Explained

1 Posts
1 Users
0 Reactions
1,268 Views
Posts: 134
Admin
Topic starter
(@sql-admin)
Reputable Member
Joined: 6 years ago

In many reporting or integration scenarios, there is often a need to convert multiple rows from a table into a single comma-separated string. This is especially helpful when preparing data for export, display, or aggregation in a summarized format.

Let’s say we have a table called employees with a list of names:

name
John
Alice
Robert

Our goal is to produce the following output:

John, Alice, Robert

This can be achieved using different SQL functions depending on the database you're working with.


SQL Server (Using STRING_AGG):

SELECT STRING_AGG(name, ', ') AS employee_list
FROM employees;

STRING_AGG() is available from SQL Server 2017 onwards and provides a clean way to concatenate rows using a delimiter.


MySQL (Using GROUP_CONCAT):

SELECT GROUP_CONCAT(name SEPARATOR ', ') AS employee_list
FROM employees;

MySQL’s GROUP_CONCAT function is simple and widely used. It automatically returns all values as a comma-separated string. You can also sort or limit the length if needed.


Oracle (Using LISTAGG):

SELECT LISTAGG(name, ', ') WITHIN GROUP (ORDER BY name) AS employee_list
FROM employees;

Oracle’s LISTAGG function is very powerful and supports ordering inside the aggregation, which is helpful for formatted outputs.


PostgreSQL (Using STRING_AGG):

SELECT STRING_AGG(name, ', ') AS employee_list
FROM employees;

PostgreSQL’s STRING_AGG works the same way as SQL Server's, making it easy to use for dynamic row-to-string conversion.


These built-in aggregation functions reduce the need for loops or custom stored procedures, and they are efficient even for large datasets. You can apply filters, group by departments, or combine with other aggregate functions to generate powerful reports.

For example, to get a comma-separated list of employee names department-wise:

SELECT department, STRING_AGG(name, ', ') AS employees
FROM employees
GROUP BY department;

This query returns one row per department, with all employee names merged together in a single field.

 


Leave a reply

Author Name

Author Email

Title *

 
Preview 0 Revisions Saved
Share: