The GROUP_CONCAT() function in SQL is used to combine multiple row values into a single string โ itโs especially useful when you want to display related values in one line instead of multiple rows.
For example, if I have a table called Students and I want to list all student names grouped by their class, I can write:
SELECT Class, GROUP_CONCAT(StudentName) AS Students
FROM Students
GROUP BY Class;
If the Students table has this data:
| Class | StudentName |
|---|---|
| 10A | Ravi |
| 10A | Priya |
| 10A | Karthik |
| 10B | Meena |
The output will be:
| Class | Students |
|---|---|
| 10A | Ravi,Priya,Karthik |
| 10B | Meena |
So, GROUP_CONCAT() takes all the student names from the same class and joins them into a single comma-separated string.
In one of my reporting projects, I used GROUP_CONCAT() to display all product names purchased in each order on a single line instead of showing multiple rows per order. It made the summary report much easier to read.
You can also customize the separator using the SEPARATOR keyword. For example:
SELECT Class, GROUP_CONCAT(StudentName SEPARATOR ' | ') AS Students
FROM Students
GROUP BY Class;
This will separate names with a โ|โ symbol instead of a comma.
A few things to note:
GROUP_CONCAT()is available in MySQL and SQLite, but in other databases like SQL Server, you useSTRING_AGG()instead.- Thereโs a length limit on the concatenated string (
group_concat_max_lenin MySQL), so for very large text results, you may need to increase that setting.
So, in short โ GROUP_CONCAT() helps you combine multiple values from grouped rows into a single text field, making it great for summary or display-oriented queries.
