[Solved] SQL query performance optimisation - fetching max(B) for corresponding A

EverSQL Database Performance Knowledge Base

SQL query performance optimisation - fetching max(B) for corresponding A

I have a database scheme that looks like this (see http://sqlfiddle.com/#!2/4c9b4/1/0 ):

 create table t( id int,  dataA int, dataB int);
 insert into t select 1 ,1 ,1;
 insert into t select 2 ,1 ,2;
 insert into t select 3 ,1 ,3;
 insert into t select 4 ,2 ,1;
 insert into t select 5 ,2 ,2;
 insert into t select 6 ,2 ,4;
 insert into t select 7 ,3 ,1;
 insert into t select 8 ,3 ,2;
 insert into t select 9 ,4 ,1;

And an SQL query to fetch a list of "dataA" for the maximum "dataB" corresponding to "dataA"

SELECT * FROM t a WHERE dataB = (SELECT MAX(dataB) FROM t b WHERE b.dataA = a.dataA)

It works OK, however it can take up to 90 seconds to run on my dataset.

How can I improve performance of this query ?

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: 2): 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 Subselect When Selecting MAX/MIN Per Group (query line: 7): Constant subquery results are usually not cached by the database, especially in non-recent database versions. Therefore, a constant subquery in a WHERE clause will be fully evaluated for every row the WHERE clause will examine, which can significantly impact query performance. Use the method mentioned in the example instead.
  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.
Optimal indexes for this query:
ALTER TABLE `t` ADD INDEX `t_idx_datab_dataa` (`dataB`,`dataA`);
The optimized query:
        t AS t1 
        t AS t2 
            ON (
                t2.dataA = t1.dataA
            AND (
                t1.dataB < t2.dataB
            1 = 1
        AND (
            t2.dataB IS NULL

Related Articles

* original question posted on StackOverflow here.