'How to order by, a json_object in mysql
Solution 1:[1]
You can't control the order of the elements in the array that json_arrayagg() generates, even in MySQL 8.0, as explained in the documentation:
Aggregates a result set as a single JSON array whose elements consist of the rows. The order of elements in this array is undefined.
An ugly and not scalable work around is to use group_concat() to manually generate the json array:
select
dashboard,
widget,
...
concat(
'[',
group_concat(
json_object('color_mode', color_mode, ...)
order by <your_ordering_clumn>
),
']'
) js_array
from datadog_wigets_markers
group by dashboard, widget, ...
This will fail on long json strings. I would rather try and live with json_arrayagg() and unordered arrays.
Side note: you should enumerate all the non-aggregated columns in the group by clause; it's a requirement in most databases, and a good coding practice.
Solution 2:[2]
@Gordon Linoff's answer from this post worked for me on MySQL 8.0, but I didn't test it for scalability.
As written in @Simas Jonelinuas's comment, here is the answer from the post in case the link ever becomes invalid.
SELECT A, json_arrayagg(json_obj('X',value1, 'Y',value2)) AS RESULT
FROM (SELECT . . .,
ROW_NUMBER() OVER (ORDER BY value2) as seqnum
FROM . . .
. . .
) x
GROUP BY A;
Quote: "The ROW_NUMBER() -- apparently -- manages to order the result set, even though ORDER BY does not work."
Solution 3:[3]
As workaround, instead:
select json_arrayagg(...) from someTable order by ...
You can:
select json_arrayagg(...) from (select someFields from someTable order by ...) as t1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GMB |
| Solution 2 | |
| Solution 3 | ktretyak |

