Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Code: 1292. Truncated incorrect time value

Tags:

sql

mysql

SELECT *
FROM SESSIONS
WHERE TIME_TO_SEC(TIMEDIFF(NOW(), SESSION_CREATED)) / 3600 >= 24

This give me 2 results

DELETE FROM SESSIONS
WHERE TIME_TO_SEC(TIMEDIFF(NOW(), SESSION_CREATED)) / 3600 >= 24

And this give me: "Error Code: 1292. Truncated incorrect time value"

SESSION_CREATED is TIMESTAMP Datatype

Actual data:

SESSION_ID      SESSION_CREATED
223133          2017-05-22 07:14:34
223134          2017-05-22 07:14:36

How can the select work but not the delete?

like image 373
Vlad C Avatar asked May 24 '17 10:05

Vlad C


2 Answers

Why are you using such a complicated expression? Why not just do:

DELETE FROM SESSIONS
    WHERE SESSION_CREATED < NOW() - INTERVAL 1 DAY;

As for why your code might fail, it is using timediff() which is limited to the range of the time data type. And this is:

MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or 'HHH:MM:SS' format for large hours values). TIME values may range from '-838:59:59' to '838:59:59'.

Because you are using NOW(), the values change from one iteration to the next. You just happened to run the SELECT when the data wasn't too old and then the DELETE when it was.

like image 181
Gordon Linoff Avatar answered Nov 19 '22 01:11

Gordon Linoff


Example for Timediff using TIMESTAMPDIFF on MySQL:

To use TIMESTAMPDIFF, define the unit (SECOND, MINUTE, HOUR...), the initial and end date (must be timestamp's datatype).

ROUND( TIMESTAMPDIFF(HOUR, initial_date, CURRENT_TIMESTAMP()) / 24, 2 )
like image 1
Tito Parizotto Avatar answered Nov 19 '22 02:11

Tito Parizotto