Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL GROUP_CONCAT with Nulls

Is there an option to make MySQL's Group_Concat function include nulls?

Consider the following example from my source table:

userId, questionId, selectionId 7, 3, NULL 7, 4, 1 7, 5, 2 

When I query on the selection table with GROUP_CONCAT, I get the following:

7, 4=1,5=2 

I would like to get the following:

7, 3=NULL,4=1,5=2 

For reference, my query looks like this:

Select userId, GROUP_CONCAT(CONCAT(questionId, '=', selectionId)) From selection Group by userId; 

I also tried adding an IFNULL like this:

Select userId, GROUP_CONCAT(IFNULL(CONCAT(questionId, '=', selectionId), 'NULL')) From selection Group by userId; 

but that produced the following:

7, NULL,4=1,5=2 

Note - There is one other complexity that I forgot to include. The selectionId is a foreign key to another table. I use a left outer join to the selection_text table. My real query includes fields from that table (these fields resolve to NULL since the selectionId is null).

like image 671
David Avatar asked Apr 26 '12 14:04

David


People also ask

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.

What does Group_concat do in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

Is there a limit to Group_concat?

The GROUP_CONCAT() function has a default length of 1024 characters, which is controlled by the global variable group_concat_max_len . If the joined values length is greater than the group_concat_max_len value, then the result string will be truncated.

Can we use Group_concat in SQL Server?

MySQL has the GROUP_CONCAT() function that allows us to output our query results in a comma separated list: SELECT GROUP_CONCAT(PetName) FROM Pets; Oracle Database. SQL Server.


2 Answers

You should just IFNULL the column that can be NULL;

SELECT userId, GROUP_CONCAT(CONCAT(questionId, '=',                   IFNULL(selectionId, 'NULL'))) FROM selection GROUP BY userId; 

Demo here.

like image 54
Joachim Isaksson Avatar answered Oct 06 '22 13:10

Joachim Isaksson


You should use IFNULL or COALESCE on the selectionId value directly:

SELECT   userId,   GROUP_CONCAT(CONCAT(questionId, '=', COALESCE(selectionId, 'NULL'))) FROM selection GROUP BY userId; 
like image 38
Dmytro Shevchenko Avatar answered Oct 06 '22 12:10

Dmytro Shevchenko