// dates & times reference

SQL millisecond function

Returns the sub-second part of a timestamp: SQL Server via DATEPART, MySQL via MICROSECOND(), SQLite via the %f format. PostgreSQL's version keeps the whole seconds.

카테고리
Dates & times
Returns
integer
In this category
47 of 121

구문

DATEPART(millisecond, ts)  -- SQL Server
EXTRACT(milliseconds FROM ts)  -- PostgreSQL
MICROSECOND(ts)  -- MySQL

Each block is a separate form. The support table and the examples show which engine takes which.

엔진 지원

엔진Support메모
SQL Server Different name or syntax DATEPART(millisecond | microsecond | nanosecond, ts)
PostgreSQL Different name or syntax EXTRACT(milliseconds FROM ts) includes the whole seconds
MySQL 예 MICROSECOND(ts) returns the fraction in microseconds
SQLite Different name or syntax strftime('%f', ts) returns 'SS.FFF' text
Oracle Different name or syntax TO_CHAR(SYSTIMESTAMP, 'FF3') for milliseconds

예시

SQL Server

SELECT DATEPART(MILLISECOND, SYSDATETIME()) AS ms;

PostgreSQL

SELECT FLOOR(EXTRACT(milliseconds FROM ts))::int % 1000 AS ms FROM events;

SQLite

SELECT strftime('%f', 'now') AS sec_frac;

알아 두면 좋은 정보

  • SQL Server's datetime rounds to 1/300 s; DATEPART(millisecond) on it returns 0, 3 and 7 increments; datetime2 is the precise type.
  • PostgreSQL's EXTRACT(milliseconds) is the seconds field times 1000, whole seconds included: 31.5 seconds gives 31500. Take it modulo 1000 for the fraction alone.
  • SQLite's %f is the whole 'seconds.fraction' string like 31.123; the fraction alone needs substr after the dot.

Questions about MILLISECOND / MICROSECOND

Why does SQL Server show .003-style milliseconds?

The datetime type rounds to 1/300 second. SYSDATETIME() with datetime2 gives true 100-ns precision for sub-second work.

How do I store millisecond precision?

Use datetime2(3) on SQL Server, timestamp(3) on PostgreSQL and Oracle, DATETIME(3) on MySQL, and TEXT ISO strings on SQLite.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.