MySQL GROUP BY and concatenate

Last updated on

If you have a table like this

id         color
----------------
1          red
1          blue
2          green

And want to group and concatenate to create this

id         color
----------------
1          red, blue
2          green

Try the following.

SELECT id, GROUP_CONCAT(color SEPARATOR ', ') FROM yourtable GROUP BY id;

The GROUP_CONCAT function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

Leave a reply

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