MySQL: GROUP_CONCAT() reference
24 September 2023 (Updated 28 September 2023)
On this page
In a nutshell
The GROUP_CONCAT()
function lets you concatenate column values from multiple rows into a single string. It’s often used with GROUP BY
to join the list of column values for rows within each group.
An example should make it clearer.
Example usage
Suppose you had a students
table like the below:
student_id | subject |
1 | Maths |
1 | Science |
2 | English |
3 | Math |
3 | English |
And you want to find the subjects each student is studying by returning the results like so:
student_id | subjects |
1 | Math, Science |
2 | English |
3 | Math, English |
You can use GROUP_CONCAT
to achieve get the desired result:
SELECT
student_id,
GROUP_CONCAT(subject) as subjects
FROM
students
GROUP BY
student_id;
By default, GROUP_CONCAT()
will separate each column value with a comma but you can also specify a different separator like so:
GROUP_CONCAT(subject SEPARATOR '; ') as subjects
Tagged:
MySQL
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment