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

  • vipin
    This is very interesting function
  • vinuthomas
    You can define your separator -
    GROUP_CONCAT(client_id SEPARATOR ':')
    Check the GROUP_CONCAT definition over at:
    http://gourl.in/2d
  • iftee
    what if I want to separate them with something different than just " , " (comma).

    thanks in advance..
  • Hrashad M
    This is really a very useful function in Business Logic !!
    Thank You...
blog comments powered by Disqus