sajad torkamani

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_idsubject
1Maths
1Science
2English
3Math
3English

And you want to find the subjects each student is studying by returning the results like so:

student_idsubjects
1Math, Science
2English
3Math, 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

Leave a comment

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