// dialect comparison

Current timestamp and its precision in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

The now() you call is not always the now you think: rounding and transaction freezing both apply.

Filed under Types & casting

The verdict

Know both knobs: precision (SYSDATETIME, NOW(6), SYSTIMESTAMP) and semantics (PostgreSQL freezes per transaction, MySQL's SYSDATE does not). For ordering events, pick the finest precision your engine offers.

Where they differ

Two subtleties hide in 'current timestamp': how many fractional digits you get, and whether repeated calls in one statement or transaction agree. Both differ by engine and by function.

How each engine writes it

SQL Server

SELECT SYSDATETIME(), GETDATE();

GETDATE rounds to ~3ms (datetime); SYSDATETIME gives datetime2(7) at 100ns. There is also SYSUTCDATETIME() for UTC.

PostgreSQL

SELECT NOW(), CLOCK_TIMESTAMP();

NOW()/transaction_timestamp() is fixed for the whole transaction, so every row in one INSERT gets the same value; CLOCK_TIMESTAMP() reads the actual clock each call.

MySQL

SELECT NOW(6), NOW();

NOW() defaults to second precision; NOW(6) gives microseconds. NOW() returns the time the statement started, while SYSDATE() reads the real clock at each call.

SQLite

SELECT STRFTIME('%Y-%m-%d %H:%M:%f', 'now');

'now' is fixed for the duration of one statement, and %f renders seconds with milliseconds (SS.SSS).

Oracle

SELECT SYSTIMESTAMP, SYSDATE FROM dual;

SYSDATE has second resolution; SYSTIMESTAMP carries fractional seconds and a zone. SYSDATE and SYSTIMESTAMP use the database server's OS time zone; LOCALTIMESTAMP and CURRENT_TIMESTAMP use the session time zone.

Questions that come up

Why do all rows in my PostgreSQL batch share a timestamp?

NOW() and CURRENT_TIMESTAMP are transaction timestamps, deliberately stable within the transaction for consistency. CLOCK_TIMESTAMP() varies per call if you need wall-clock sampling.

Why does GETDATE() repeat values across rows?

datetime only has ~3ms resolution, so fast inserts collide. Use SYSDATETIME() with a datetime2 column for finer ordering.

Which function gives UTC?

SYSUTCDATETIME() in SQL Server, NOW() AT TIME ZONE 'UTC' in PostgreSQL, UTC_TIMESTAMP() in MySQL, DATETIME('now') in SQLite (already UTC), and SYS_EXTRACT_UTC(SYSTIMESTAMP) in Oracle.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.