Search code examples
mysqldatabasemariadbgroup-concat

Order between multiple GROUP_CONCAT columns


I can't seem to find any information about GROUP_CONCAT function default behavior, maily when i use multiple of those, will the returned values have the same order in between them?

For this example table & data:

CREATE TABLE `test` (
  `id` int(11) NOT NULL,
  `parentId` int(11) NOT NULL,
  `weight` int(11) NOT NULL,
  `color` varchar(7) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `test` (`id`, `parentId`, `weight`, `color`) VALUES
(1, 1,  500,    '#aa11dd'),
(2, 1,  770,    '#ffffff'),
(3, 2,  100,    '#ff00ff'),
(4, 2,  123,    '#556677');

If I do this select:

SELECT `parentId`, 
        GROUP_CONCAT(`weight`), 
        GROUP_CONCAT(`color`), 
        GROUP_CONCAT(`id`) 
FROM `test` 
GROUP BY `parentId`

It returns:

parentId    GROUP_CONCAT(weight)    GROUP_CONCAT(color)     GROUP_CONCAT(id)
1           500,770                 #aa11dd,#ffffff         1,2
2           79798,123               #ff00ff,#556677         3,4

Is it ever possible that for example in the first line values 500,770 will flip into 770,500 but the rest of columns remain the same (#aa11dd,#ffffff; 1,2)? I don't really care about the overall order (DESC / ASC), all i want to know is, if each column has always the same order as the others?


Solution

  • In the absence of the ORDER BY clause inside the GROUP_CONCAT() function the engine is free to assemble the value in any order, and this order is not stable over time. Each GROUP_CONCAT() function may have a different ordering as well.

    To ensure a stable ordering use ORDER BY inside the GROUP_CONCAT() function.

    For example;

    SELECT
      `parentId`, 
      GROUP_CONCAT(`weight` order by `id`), 
      GROUP_CONCAT(`color` order by `id`), 
      GROUP_CONCAT(`id` order by `id`) 
    FROM `test` 
    GROUP BY `parentId`
    

    This example orders all values by id to ensure a stable, known order, and also to ensure that each column has always the same order as the others.