Migrating MySQL database to TiDB: Data retrieved using GROUP BY statement is unordered if ORDER BY is not added

Note:
This topic has been translated from a Chinese forum by GPT and might contain errors.

Original topic: 迁移mysql库到tidb,使用 group by 语句如果不加 order by ,查出来的数据是乱序的

| username: yingguonanbu

【TiDB Usage Environment】Production Environment
【TiDB Version】v4.0.8
【Encountered Problem】
After migrating the MySQL database to TiDB, since the business previously used MySQL and all query statements used GROUP BY without adding ORDER BY, the results in MySQL would always remain the same. However, in TiDB, the order of the query results changes every time. This causes the business statistics displayed on the web page to be disordered. (Because our old project SQLs do not have ORDER BY, modifying the business SQLs would be too costly, requiring changes to hundreds of statements.)
【Reproduction Path】
【Help Needed】
Is there a way to use GROUP BY in TiDB without adding ORDER BY (since modifying hundreds of SQL statements in the business is too costly) and still have the results sorted in the same order as in MySQL, instead of having the results in a different order each time?
【Problem Phenomenon and Impact】

Comparison of two query results using GROUP BY in TiDB, showing the order has changed:
First query using TiDB:

Second query using TiDB:

Query results using MySQL, showing automatic sorting by the timestamp field:

| username: yingguonanbu | Original post link

I need help from everyone, this is already affecting our production environment. Is this a compatibility issue between TiDB and MySQL?

| username: ddhe9527 | Original post link

In MySQL version 5.7, GROUP BY implicitly includes a sorting function. Starting from MySQL 8.0, this implicit sorting is no longer present. Therefore, if your business logic strongly depends on sorting, it is best to explicitly add ORDER BY and not rely on this hidden feature in MySQL 5.7.

| username: Kongdom | Original post link

When not specified, is it sorted by the primary key?

| username: ddhe9527 | Original post link

MySQL sorts by the fields following the group by clause.

| username: yingguonanbu | Original post link

Is there any configuration in TiDB to add a default sort order?

| username: ddhe9527 | Original post link

As far as I know, there isn’t.

| username: yingguonanbu | Original post link

Okay, thanks.

| username: system | Original post link

This topic was automatically closed 1 minute after the last reply. No new replies are allowed.