Thursday 24 July 2014

Using Group_Concat() function in MySQL - Handy function to extract all values of a column

The Group_Concat() function in MySQL saved the day for me this week. So, a post thanking the authors. :)

I was loading some basic geographical data of Users who logged in to a website. The data looked as follows:

Row_id Language Name
42914 ES Reader1
42915 ES Reader1
44623 EN Reader1
44624 EN Reader1
44625 EN Reader1

The dataset is actually pretty heavy with lots of other columns. So, my objective was to have a single row for 'NAME' with all the languages he uses in a delimited format. 

For example, the result output should become:

Name  Languages
Reader1 ES | EN
Reader2 EN | AR
And the group_concat() function in MySQL was just what I was looking for.

Example query:

select
 Name
, group_concat(distinct actor_languages separator '|')
 from tweet_data
group by Name
;

The query will group your dataset by Name, and create a pipe separated string of all the languages in the language column.
Please remember to use distinct. Else, we will have one entry for each row of Name, and this will become a really long string.

Suggestions or comments are welcome as always !!


No comments:

Post a Comment

Please share your thoughts and let us know the topics you want covered