5 September 2006 View Comments

GROUP_CONCAT in MySQL

GROUP_CONCAT(expr) – This function returns a string result with the concatenated non-NULL values from a group.

Where it can be useful?

For example to get PHP array without looping inside PHP:
CREATE TABLE services (
id INT UNSIGNED NOT NULL,
client_id INT UNSIGNED NOT NULL,
KEY (id));
INSERT INTO services
VALUES (1,1),(1,2),(3,5),(3,6),(3,7);
SELECT id,client_id FROM services WHERE id = 3;
+----+-----------+
| id | client_id
+----+-----------+
| 3 | 5
| 3 | 6
| 3 | 7
+----+-----------+
SELECT id,GROUP_CONCAT(client_id) FROM services WHERE id = 3 GROUP BY id;
+----+-------------------------+
| id | GROUP_CONCAT(client_id)
+----+-------------------------+
| 3 | 5,6,7
+----+-------------------------+

Read more: MySQL Performance Blog » GROUP_CONCAT useful GROUP BY extension

View Comments to “GROUP_CONCAT in MySQL”

  1. Hrashad M 13 November 2008 at 3:24 pm #

    This is really a very useful function in Business Logic !!
    Thank You…

  2. iftee 14 February 2009 at 3:11 am #

    what if I want to separate them with something different than just ” , ” (comma).

    thanks in advance..

  3. vinu 15 February 2009 at 9:41 am #

    You can define your separator -
    GROUP_CONCAT(client_id SEPARATOR ‘:’)
    Check the GROUP_CONCAT definition over at:
    http://gourl.in/2d

  4. vipin 18 April 2009 at 4:21 am #

    This is very interesting function

  5. vipin 18 April 2009 at 8:21 am #

    This is very interesting function

  6. Nishant 19 April 2010 at 12:55 pm #

    SELECT GROUP_CONCAT(userId SEPARATOR ':') FROM …..

  7. Sanjay Soral 25 July 2010 at 7:04 am #

    Outstanding function, Thank you Very Much. Great………


Leave a Reply

blog comments powered by Disqus