Get the next datetime value

All we need is an easy explanation of the problem, so here it is.

I have a MySQL table:

SELECT 
    sh.id,
    sh.DG_ID,
    sh.START_DATE
FROM 
    STATUS_HISTORIES sh
order by DG_ID, START_DATE
id DG_ID START_DATE
22 212 2021-04-20 14:59:58
66 212 2021-04-21 05:01:25
110 212 2021-04-21 14:58:31
157 212 2021-04-22 05:00:40

I want to get next datetime value or null if next datetime value doesn’t exist. Like this:

id DG_ID START_DATE next_start_date
22 212 2021-04-20 14:59:58 2021-04-21 05:01:25
66 212 2021-04-21 05:01:25 2021-04-21 14:58:31
110 212 2021-04-21 14:58:31 2021-04-22 05:00:40
157 212 2021-04-22 05:00:40 NUll

I tried doing this:

SELECT 
    sh.id,
    sh.DG_ID,
    sh.START_DATE,
    sh2.START_DATE as next_start_date
FROM 
    STATUS_HISTORIES sh
    left join STATUS_HISTORIES sh2 on sh2.id = sh.id and sh2.START_DATE > sh.START_DATE 
order by sh.DG_ID, sh.START_DATE

but got null:

id DG_ID START_DATE next_start_date
22 212 2021-04-20 14:59:58 null
66 212 2021-04-21 05:01:25 null
110 212 2021-04-21 14:58:31 null
157 212 2021-04-22 05:00:40 null

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can use the LEAD window function in MariaDB 10.2+, MySQL version 8.0+, and SQL Server 2012

SELECT 
    sh.id,
    sh.DG_ID,
    sh.START_DATE,
    LEAD(sh.START_DATE) OVER (
        PARTITION BY sh.DG_ID ORDER BY sh.START_DATE) as next_start_date
FROM 
    STATUS_HISTORIES sh
ORDER BY sh.DG_ID, sh.START_DATE

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply