Skip to content

ORDER BY in JSON_ARRAYAGG() #28997

@hooopo

Description

@hooopo

Feature Request

I found that TiDB already supports the json_arrayagg function, which can replace the old group_concat function in simple scenarios. But for scenes with sorting requirements, the json_arrayagg function cannot be satisfied.

CREATE TABLE test (
  id INT
);
INSERT INTO test (id) VALUES (3);
INSERT INTO test (id) VALUES (1);
INSERT INTO test (id) VALUES (2);

Use group_concat with order by

select group_concat(id order by id asc) as str from test group by id div 2;
+------+
| str |
+------+
| 2,3 |
| 1 |
+------+

TiDB json_arrayagg

select json_arrayagg(id order by id asc) as arr from test group by id div 2;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your TiDB version for the right syntax to use line 1 column 29 near "order by id asc) as arr from test group by id div 2 "

without order by:

select json_arrayagg(id) as arr from test group by id div 2 ;
+--------+
| arr    |
+--------+
| [1]    |
| [3, 2] |
+--------+
--the order of the results is wrong

MariaDB 10.5

select json_arrayagg(id order by id asc) as arr from test group by id div 2;

+------+
| arr |
+------+
| [2,3] |
| [1] |
+------+

Metadata

Metadata

Assignees

No one assigned

    Labels

    type/feature-requestCategorizes issue or PR as related to a new feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions