HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

Is it possible to automatically generate a Unix millisecond timestamp in MySQL 5.7

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
unixautomaticallymillisecondpossiblegeneratemysqltimestamp

Problem

I have created a created_time field with BIGINT in a MySQL 5.7 table, now I want to auto generate a Unix millisecond timestamp when I insert a record. Is it possible to do this? I have tried the code below but it failed:

ALTER TABLE db.video_info MODIFY COLUMN created_time bigint(20) 
  DEFAULT (ROUND(UNIX_TIMESTAMP(CURTIME(4)) * 1000)) NULL;

Solution

MySQL 8.0 supports the expression default like you show.

MySQL 5.7 does not support expressions as default. Only NULL, or a constant value, or CURRENT_TIMESTAMP if it's a DATETIME or TIMESTAMP column.

For MySQL 5.7, you have two alternatives:

-
Declare the column as created_time datetime(3) default current_timestamp(3).

-
Use BIGINT as you are doing, but write a trigger to set the value.

Context

StackExchange Database Administrators Q#288926, answer score: 6

Revisions (0)

No revisions yet.