GROUP_CONCAT in MySQL

GROUP_CONCAT() is a function that merges the data from multiple rows into one field. It is a GROUP BY function that returns a string. The comma (,) or any user-specified delimiter can be used to separate the values in the string.

To know more about this function and similar functionality in various RDBMS and big data technologies, please click here. Please also read Multi group_concat in a single query with distinct mysql

We’ll look at how to use the GROUP CONCAT function with the GROUP clause in this post. This is used to combine the categorized values into a single row for each category.

Here is an example:

CREATE TABLE tbStudents(iStudentID INT, StudentName VARCHAR(10), SubjectName VARCHAR(30));

INSERT INTO tbStudents VALUES

(1, ‘John’, ‘Mathematics’),
(1, ‘John’, ‘Science’),
(1, ‘John’, ‘Chemistry’),
(2, ‘Smith’, ‘Economics’),
(2, ‘Smith’, ‘Mathematics’),
(2, ‘Smith’, ‘Commerce’),
(3, ‘Will’, ‘History’),
(3, ‘Will’, ‘Civics’),
(3, ‘Will’, ‘Economics’);

SELECT iStudentID, StudentName,GROUP_CONCAT(SubjectName)
FROM tbStudents
GROUP BY iStudentID, StudentName;

GroupConcat_MySQL

Hope this helps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s