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.
- Categoría
- Dates & times
- Returns
integer- In this category
- 47 of 121
Sintaxis
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.
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| 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 | Sí | 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 |
Ejemplos
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;
Conviene saberlo
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.