9

I want to order the array returned by json_arrayagg(). My query is similar to this:-

select A, json_arrayagg(json_obj('X',value1, 'Y',value2)) AS RESULT
FROM (derived table)
GROUP BY A.

What I want is that I want the array that returns to be ordered by value2. I have tried adding order by clause at the end (like, order by value2: it is not working)

have tried adding order by inside json_arrayagg()..(like: json_arrayagg(json_obj() order by value2) It is not working.

Have tried using group_concat , but it is not reliable and don't know why it's not returning correct data. Have checked limits.

Please suggest me how to solve this? Thanks

3
  • @Gordon Linoff, Can you please help here! Commented Aug 5, 2020 at 4:54
  • . . Unfortunately, MySQL does not formally support that functionality -- even with an ORDER BY in the subquery. There is a hacky solution but no guarantee that that works. Commented Aug 5, 2020 at 11:13
  • @Gordon Linoff, There was no shortcut to do it, so I tried to pass the ordered values from the required derived table to the JSON_ARRAYAGG. But still, I would like to know the hacky solution ~ Thanks :) Commented Aug 6, 2020 at 3:23

3 Answers 3

4

Apparently, there is a hack which might work:

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;

The ROW_NUMBER() -- apparently -- manages to order the result set, even though ORDER BY does not work.

Sign up to request clarification or add additional context in comments.

1 Comment

About 5yrs later, is there any better way? BTW @Gordon Linoff - your profile has the old edition linked for your book, and your domain has expired.
2

Im facing the same problem, in the end i use GROUP_CONCAT instead:

select 
    A, 
    CONCAT('[',
      GROUP_CONCAT(JSON_OBJECT('X',value1, 'Y',value2) ORDER BY value0)
    ,']') AS RESULT
FROM (derived table)
GROUP BY A.

Comments

1

I found out that on recent versions of MySQL (8+), the order can be set if a limit is explicitely provided in the recordset sent to json_arrayagg , otherwise this is not applied at all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.