I'm trying to get a Java-style long timestamp, that is, UNIX timestamp with millisecond precision * 1000, which fits into a non-floating-point type (BIGINT).
I didn't find a way to get it straight from some function, like CURRENT_TIMESTAMP, unless I was okay with formatting like 20181010123059123.
So I found that this would give me something that looks like a number:
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
-- Gives: 23649115.452000
Note that I am substracting 2018-... since I only care about the delta, not the absolute date.
I am not sure if this is the simples way.
Turns out the type of this is INTERVAL, so I need to convert:
CAST(
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
AS DECIMAL(15,3)
)
-- Gives 23649115.000
Now the issue is, the precision is lost.
So I wonder: Where is the .452 lost and how can I keep it? This is what the manual says:
An interval value can be cast to a numeric type. In this case the interval value is first converted to a single-field INTERVAL type with the same field as the least significant filed of the interval value. The value is then converted to the target type. For example CAST (INTERVAL '1-11' YEAR TO MONTH AS INT) evaluates to INTERVAL '23' MONTH, and then 23.
And the ultimate question is:
How can I get UNIX timestamp-like number of milliseconds since some moment, e.g. UNIX epoch start?
My current whole SQL:
SELECT
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND,
FLOOR(
CAST(
(CURRENT_TIMESTAMP - TIMESTAMP '2018-01-01 00:00:00') SECOND TO SECOND
AS DECIMAL(15,3)
) * 1000
)
FROM (VALUES(0));
-- Gives: 23649115.452000 | 23649115000
Turns out there's
UNIX_MILLISwhich I overlooked (because the broken PDF format manual prevents proper searching).Which renders my attempts above a nice excercise in intervals.
I still wonder, how should I
CASTan interval to retain the milliseconds part.