[Solved] SQL return second max date for each id, date and channel

EverSQL Database Performance Knowledge Base

SQL return second max date for each id, date and channel

I have the following table:

id  channel_id     date
1 | 1           | 2017-01-10
1 | 2           | 2018-02-05
1 | 1           | 2019-03-07
1 | 2           | 2020-03-15
2 | 1           | 2018-01-17
2 | 1           | 2019-07-20
2 | 1           | 2020-01-10

I want to return for previous maximum date for each date and id but two separate columns for both channel_id. So, one column for previous max date for channel_id is equal to 1 and another for previous max date for channel_id is equal to 2. What I want to get can be found below:

id  channel_id       date      prev_date_channel_id1    prev_date_channel_id2     
1 | 1           | 2017-01-10 |    NULL               |    NULL                |
1 | 2           | 2018-02-05 |    2017-01-10         |    NULL                |
1 | 1           | 2019-03-07 |    2017-01-10         |    2018-02-05          |
1 | 2           | 2020-03-15 |    2019-03-07         |    2018-02-05          | 
2 | 1           | 2018-01-17 |    NULL               |    NULL                |
2 | 1           | 2019-07-20 |    2018-01-17         |    NULL                |
2 | 1           | 2020-01-10 |    2019-07-20         |    NULL                |

I made a query as below and returns what I want but takes too much time. I'd appreciate any optimization suggestions!

SELECT 
    a.id,
    a.date,
    MAX(c.date) AS prev_date_channel_id1, 
    MAX(d.date) AS prev_date_channel_id2    
FROM 
    table a         
LEFT JOIN
    table c ON a.id=c.id AND a.date>c.date AND c.channel_id=1
LEFT JOIN
    table d ON a.id=d.id AND a.date>d.date AND d.channel_id=2
GROUP BY a.id, a.date

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. 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.
  2. 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_channel_id_id_date` (`channel_id`,`id`,`date`);
The optimized query:
SELECT
        a.id,
        a.date,
        MAX(c.date) AS prev_date_channel_id1,
        MAX(d.date) AS prev_date_channel_id2 
    FROM
        table a 
    LEFT JOIN
        table c 
            ON a.id = c.id 
            AND a.date > c.date 
            AND c.channel_id = 1 
    LEFT JOIN
        table d 
            ON a.id = d.id 
            AND a.date > d.date 
            AND d.channel_id = 2 
    GROUP BY
        a.id,
        a.date 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.