Tuesday, November 06, 2012

MYSQL :: Concatenation of columns in multiple rows

Suppose, we have a table as shown below ::

ID Animal_name
1 Lion
2 Tiger
3 Monkey
4 Horse
The "animal_table" table

Suppose, the table has a name "animal_table". Now, I want to have all the values in the "Animal_name" column to be merged into a single string. We can do it in MySQL itself with the help of "GROUP_CONCAT" function as shonw below.

SELECT group_concat( `Animal_name` SEPARATOR ', ' ) FROM `animal_table` 

The output is shown below :
Lion, Tiger, Monkey, Horse

The phrase "SEPARATOR ', '" actually defines the glue string which merges the values together.

If we want the whole table sorted before the concatenation, we would write the query as follows.

SELECT group_concat( DISTINCT `Animal_name` ORDER BY `Animal_name` SEPARATOR ', ' ) FROM `animal_table`

"DISTINCT" has to be used with "ORDER BY" clause.

No comments: