Query to find the difference between successive rows in Mysql

Deepak Mani picture Deepak Mani · Mar 14, 2012 · Viewed 10.8k times · Source

As I am new to MySQL, this question may be silly. How can I find the difference between successive rows?
Example:
A table (tableName='Abc') contains a single row as follows,

|DATA|
|10  |
|20  |
|30  |
|40  |
|50  |

Here I want get the output as,

|Dif|
|10 |
|10 |
|10 |
|10 |

How to find the difference like this without any index (primary or Auto_increment)?

Answer

John Pick picture John Pick · Mar 14, 2012

A self-join is one way to compare consecutive rows:

SELECT
    MIN(T2.DATA - T1.DATA) AS Dif
FROM
    Abc T1 INNER JOIN Abc T2 on T1.DATA < T2.DATA
ORDER BY
    T1.DATA