[Solved] MySQL - ORDER BY and GROUP BY together
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

MySQL - ORDER BY and GROUP BY together

Database type:

I am using an external DB and I have 3 important columns: user_id, total_score, score_order.

I would like to get the total_score of each user.

All the scores are always recorded, so I only need the last one. For this I need to use the score_order column.

This is what I am trying to do (using nested queries because I need to combine ORDER BY and GROUP BY):

SELECT * FROM (
    SELECT * FROM `table` ORDER BY score_order DESC
) AS tmp_table GROUP BY user_id

But I get the error:

'#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'tmp_table.ranking_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by Can someone explain what I am doing wrong?'

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 5): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. Avoid Subqueries (query line: 4): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, it's recommended to join a newly created temporary table that holds the data, which also includes the relevant search index.
  3. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  4. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `table` ADD INDEX `table_idx_score_order` (`score_order`);
The optimized query:
SELECT
        * 
    FROM
        (SELECT
            * 
        FROM
            `table` 
        ORDER BY
            `table`.score_order DESC) AS tmp_table 
    GROUP BY
        tmp_table.user_id 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.