0

I am using MySql and I have a field of type `BIGINT(20).

I realise that I can use CURRENT_TIMESTAMP as default as explained here.

However, how do I assign, by default, a javascript-like timestamp, which includes milliseconds?

I am happy to just have the "000" at the end if there is no other way to have a millisecond-precise timestamp.

UPDATE: Please note that the question is based on leaving the column type as BIGINT(20)

1
  • I use node but this is totally unrelated to the language used Commented Apr 1, 2019 at 7:31

1 Answer 1

2

The basic answer to your question is you can't, as BIGINT columns can not have CURRENT_TIMESTAMP as a default value.

If you change your column type to TIMESTAMP(3) it will record timestamps with 3 decimal places of precision (i.e. down to milliseconds). You can have up to 6 decimal places. See the manual. In this situation you will also want to change your default to CURRENT_TIMESTAMP(3).

Demo on dbfiddle

A workaround to make it appear as if the column is a BIGINT would be to create a VIEW on the table using UNIX_TIMESTAMP for reading e.g.

CREATE VIEW jobs_us AS
SELECT ..., UNIX_TIMESTAMP(added) AS added 
FROM jobs

and use INSERT and UPDATE triggers to convert integer values to TIMESTAMP format using FROM_UNIXTIME e.g.

CREATE TRIGGER jobs_added BEFORE INSERT ON jobs
FOR EACH ROW
BEGIN
    IF NEW.added IS NOT NULL THEN
        SET NEW.added = FROM_UNIXTIME(NEW.added);
    END IF;
END
Sign up to request clarification or add additional context in comments.

9 Comments

So just ALTER TABLE jobs ALTER COLUMN added SET DEFAULT CURRENT_TIMESTAMP(3) and that's it?
It should be ALTER TABLE jobs MODIFY added TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP(3)
But I wanted the column to stay as a BIGINT(20) rather than timestamp(3)... If I run ALTER TABLE jobs MODIFY added TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP(3); I get ERROR 1292 (22007): Incorrect datetime value: '1553893854362' for column 'added' at row 1. If I run ALTER TABLE jobs MODIFY added BIGINT(20) DEFAULT CURRENT_TIMESTAMP(3); I get ERROR 1067 (42000): Invalid default value for 'added'
@Merc you can't specify CURRENT_TIMESTAMP as a default value for a BIGINT column, it can only be a default for a Date or Time type column. See my updated demo for how you can translate to/from unix timestamps using the UNIX_TIMESTAMP and FROM_UNIXTIME functions
But you can't assign a function as default right...?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.