Bug #116277 Insert rounds datetime/timestamp fractions instead of truncating
Submitted: 1 Oct 2024 14:57 Modified: 1 Oct 2024 20:52
Reporter: Mattias Jonsson Email Updates:
Status: Duplicate Impact on me:
None 
Category:MySQL Server: Data Types Severity:S2 (Serious)
Version:8.0.32 OS:Any
Assigned to: CPU Architecture:Any
Tags: datetime, insert, Rounding, truncate

[1 Oct 2024 14:57] Mattias Jonsson
Description:
INSERT seems to round the fraction part of DATETIME and TIMESTAMP columns, instead truncating them.

This can be serious when not having enough precision for a datetime column, resulting in events have the next second/minute/day/month or even year, instead of the current one! Like if something is inserted as '2023-12-31 23:59:59.511111' it is stored as '2024-01-01 00:00:00'.

For time it does not make sense to round up.

NOW() and UTC_TIMESTAMP() does truncate.

How to repeat:
create table t (dt datetime, dt6 datetime(6), ts timestamp, ts6 timestamp(6));
insert into t values (now(6), now(6), now(6), now(6));
select sleep(0.5);
insert into t values (now(6), now(6), now(6), now(6));
insert into t values (now(), now(), now(), now());
select sleep(0.5);
insert into t values (now(), now(), now(), now());
select * from t;

Results in:
+---------------------+----------------------------+---------------------+----------------------------+
| dt                  | dt6                        | ts                  | ts6                        |
+---------------------+----------------------------+---------------------+----------------------------+
| 2024-10-01 16:40:57 | 2024-10-01 16:40:57.399706 | 2024-10-01 16:40:57 | 2024-10-01 16:40:57.399706 |
| 2024-10-01 16:40:58 | 2024-10-01 16:40:57.903779 | 2024-10-01 16:40:58 | 2024-10-01 16:40:57.903779 | <= Rounded UP dt and ts!!
| 2024-10-01 16:40:57 | 2024-10-01 16:40:57.000000 | 2024-10-01 16:40:57 | 2024-10-01 16:40:57.000000 | <= Note that NOW() does truncate!
| 2024-10-01 16:40:58 | 2024-10-01 16:40:58.000000 | 2024-10-01 16:40:58 | 2024-10-01 16:40:58.000000 | 
+---------------------+----------------------------+---------------------+----------------------------+

Suggested fix:
Never round time, always truncate it!
[1 Oct 2024 20:52] Mattias Jonsson
Hmm, probably a duplicate of https://bugs.mysql.com/bug.php?id=68760.
I couldn't find it before, as well as it seems documented and a part of the SQL standard:
https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html