Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
MYSQL difference between two datetime

I have the following table.

table1:

id_user | action |  time 
--------+--------+----------------------
1       | 2      | '2009-05-18 11:45:42'
1       | 2      | '2009-05-18 11:45:45'
1       | 3      | '2009-05-18 11:45:50'
1       | 2      | '2009-05-18 11:46:50'

And I want to achieve result where the column timediff contains timediff with the previous row in seconds.

table2

id_user | action | timediff
--------+--------+----------
1       | 2      | 3
1       | 2      | 5
1       | 3      | 60

I tried this query, but It did not work:

SELECT
    id_user,action, 
    TIMESTAMPDIFF(SECOND,LEAD(time),time) OVER (PARTITION BY id_user, ORDER BY time) AS timediff
FROM table1

... but it throws an error. :/

I read other answers, but I didn't see one that use LEAD or LAG with TIMESTAMPDIFF simultaneously.

Thanks in advance.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Your syntax is wrong, you must use this:

SELECT id_user,
       action, 
       TIMESTAMPDIFF(
         SECOND, 
         time, 
         LEAD(time) OVER (PARTITION BY id_user ORDER BY time)
       )  AS timediff 
FROM table1

The TIMESTAMPDIFF() function's 2nd and 3d arguments are datetime expressions and the 2nd is subtracted from the 3d.

See the demo.
Results:

| id_user | action | timediff |
| ------- | ------ | -------- |
| 1       | 2      | 3        |
| 1       | 2      | 5        |
| 1       | 3      | 60       |
| 1       | 2      |          |
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!