Reading history

SQL GROUP_CONCAT and STRING_AGG: Combine Rows Into a String

5 min read 0 views

Learn SQL string aggregation with GROUP_CONCAT and STRING_AGG: separators, ordering inside the list, DISTINCT, joins, and splitting a list back into rows.

Most aggregate functions turn many rows into one number: COUNT, SUM, AVG. String aggregation turns many rows into one piece of text, such as “Nusrat, Tania, Mitu” for all the CSE students. It is perfect for reports, emails and dashboards where a list reads better than a column. This lesson covers GROUP_CONCAT, its standard cousin STRING_AGG, and how to split a list back into rows.

In this lesson you will learn

  • Joining values from many rows with GROUP_CONCAT and STRING_AGG
  • Choosing the separator and the order inside the list
  • Removing duplicates with DISTINCT
  • Combining string aggregation with joins
  • Splitting a comma-separated string back into rows

You should know GROUP BY and joins. The examples use the course’s sample students, courses and enrollments tables.

GROUP_CONCAT Basics

-- One row per department, with its students in a single text column
SELECT dept,
       COUNT(*) AS students,
       GROUP_CONCAT(name, ', ') AS names
FROM students
GROUP BY dept;

-- Choose the order inside the list (SQLite 3.44 or later)
SELECT dept,
       GROUP_CONCAT(name || ' (' || cgpa || ')', '; ' ORDER BY cgpa DESC) AS ranked
FROM students
WHERE cgpa IS NOT NULL
GROUP BY dept;

-- Unique values only
SELECT GROUP_CONCAT(DISTINCT city) AS cities FROM students;

Output

+------+----------+----------------------------+
| dept | students | names                      |
+------+----------+----------------------------+
| BBA  | 2        | Imran, Sabbir              |
| CSE  | 4        | Nusrat, Tania, Mitu, Nadia |
| EEE  | 2        | Arif, Rafi                 |
+------+----------+----------------------------+
(3 rows)

+------+------------------------------------------+
| dept | ranked                                   |
+------+------------------------------------------+
| BBA  | Sabbir (3.55); Imran (3.1)               |
| CSE  | Tania (3.95); Nusrat (3.82); Mitu (3.67) |
| EEE  | Arif (3.41); Rafi (2.98)                 |
+------+------------------------------------------+
(3 rows)

+-----------------------------------------+
| cities                                  |
+-----------------------------------------+
| Dhaka,Chattogram,Khulna,Sylhet,Rajshahi |
+-----------------------------------------+
(1 row)
  • GROUP_CONCAT(name, ', ') joins the names in each group with a comma and a space. Without a second argument the separator is a plain comma, as in the third query.
  • Without ORDER BY inside the function, the order of the list is not guaranteed. It often follows the table order, but you should not rely on it.
  • ORDER BY cgpa DESC inside the brackets sorts the list itself, not the result rows. Here each department’s students appear from highest to lowest CGPA.
  • Nadia has no CGPA, and name || ' (' || NULL || ')' would be NULL. NULL values are skipped by string aggregation, so the second query filters them out to make that clear.
  • DISTINCT keeps each city once, even though three students live in Dhaka.

String Aggregation With Joins

-- Courses each student takes, as one line per student
SELECT s.name,
       STRING_AGG(c.title, ' + ' ORDER BY c.title) AS courses,
       SUM(c.credits) AS total_credits
FROM students s
JOIN enrollments e ON e.student_id = s.id
JOIN courses c ON c.id = e.course_id
GROUP BY s.id
ORDER BY total_credits DESC, s.name;

-- Going back: split a comma-separated string into rows
WITH RECURSIVE split(item, rest) AS (
  SELECT '', 'Dhaka,Sylhet,Khulna' || ','
  UNION ALL
  SELECT substr(rest, 1, instr(rest, ',') - 1),
         substr(rest, instr(rest, ',') + 1)
  FROM split
  WHERE rest <> ''
)
SELECT item FROM split WHERE item <> '';

Output

+--------+-----------------------------+---------------+
| name   | courses                     | total_credits |
+--------+-----------------------------+---------------+
| Nusrat | Data Structures + Databases | 6             |
| Tania  | Data Structures + Databases | 6             |
| Arif   | Circuit Theory              | 4             |
| Rafi   | Circuit Theory              | 4             |
| Imran  | Marketing                   | 3             |
| Mitu   | Databases                   | 3             |
| Sabbir | Marketing                   | 3             |
+--------+-----------------------------+---------------+
(7 rows)

+--------+
| item   |
+--------+
| Dhaka  |
| Sylhet |
| Khulna |
+--------+
(3 rows)
  • STRING_AGG(value, separator) is the SQL standard name, used by PostgreSQL and SQL Server. SQLite 3.44+ accepts both names.
  • Grouping by s.id after two joins gives one row per student with all their course titles and their total credits.
  • Students with no enrollments (Nadia) do not appear, because an inner join needs a match. Use a LEFT JOIN if you want them listed with an empty value.
  • The second query goes the other way. A recursive CTE takes the text up to the first comma as one item, keeps the rest, and repeats until nothing is left. Adding a final comma to the input makes the last item work the same way as the others.

Splitting strings in SQL is a sign that the data should probably be stored in separate rows. Comma-separated values in one column break the first rule of normalization. Use splitting to clean up imported data, not as a long-term design.

The Same Idea in Other Databases

DatabaseFunctionExample
SQLiteGROUP_CONCAT or STRING_AGGGROUP_CONCAT(name, ', ' ORDER BY name)
MySQL / MariaDBGROUP_CONCATGROUP_CONCAT(name ORDER BY name SEPARATOR ', ')
PostgreSQLSTRING_AGGSTRING_AGG(name, ', ' ORDER BY name)
SQL ServerSTRING_AGGSTRING_AGG(name, ', ') WITHIN GROUP (ORDER BY name)

MySQL cuts the result at 1,024 characters by default. Raise the group_concat_max_len setting if your lists are long.

Common Mistakes

  1. Expecting a fixed order without ORDER BY inside the function.
  2. Concatenating a column that can be NULL. One NULL makes the whole || expression NULL, so that value silently disappears from the list. Wrap it in COALESCE.
  3. Grouping by a name instead of an id. Two students with the same name would be merged into one row.
  4. Storing lists in a column because GROUP_CONCAT makes them easy to produce. Keep the rows; build the text only for display.

Practice Exercises

Exercise 1. List each city with the names of the students who live there, in alphabetical order, separated by ” | “.

Show answer
SELECT city, GROUP_CONCAT(name, ' | ' ORDER BY name) AS students
FROM students
GROUP BY city;

Exercise 2. For each course, show the title and the names of enrolled students with their marks, best mark first, like “Tania 95, Nusrat 88”.

Show answer
SELECT c.title,
       GROUP_CONCAT(s.name || ' ' || e.marks, ', ' ORDER BY e.marks DESC) AS results
FROM courses c
JOIN enrollments e ON e.course_id = c.id
JOIN students s ON s.id = e.student_id
GROUP BY c.id;

Frequently Asked Questions

What does GROUP_CONCAT return for an empty group?

NULL, like most aggregates over no rows. Use COALESCE(GROUP_CONCAT(name), '') if you need an empty string instead.

Can I use GROUP_CONCAT without GROUP BY?

Yes. Without GROUP BY the whole result is one group, so you get a single row with every value joined together, as in the cities example.

Summary

  • GROUP_CONCAT and STRING_AGG join values from many rows into one string.
  • Put ORDER BY inside the function to control the list order.
  • DISTINCT removes repeated values; NULLs are skipped.
  • A recursive CTE can split a delimited string back into rows.

Next: UPDATE and DELETE With Joins.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *