// dates & times reference

SQL SECOND function

Returns the seconds component of a timestamp, usually for dedup keys or measuring sub-minute spreads.

类别
Dates & times
Returns
integer (fractional on PostgreSQL)
In this category
42 of 121

语法

EXTRACT(second FROM ts)
DATEPART(second, ts)  -- SQL Server
SECOND(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(second, ts); no SECOND() shorthand
PostgreSQL Different name or syntax EXTRACT(second) includes the fraction: 31.5 is valid
MySQL 是 Supported under this name.
SQLite Different name or syntax strftime('%S', ts) returns text
Oracle Different name or syntax EXTRACT needs a TIMESTAMP; DATE has no sub-second storage

示例

PostgreSQL

SELECT EXTRACT(second FROM created_at) AS s FROM orders;

SQL Server

SELECT DATEPART(second, created_at) AS s FROM orders;

MySQL

SELECT SECOND(created_at) AS s FROM orders;

值得了解

  • PostgreSQL's EXTRACT(second) includes the fraction (31.500000, not 31) and returns numeric (double precision before version 14). Use FLOOR() if you want whole seconds; a cast to int rounds.
  • SQL Server's datetime type rounds to 1/300 second, so 10:00:59.999 is stored as 10:01:00.000 and DATEPART(second) returns 0, not 59.
  • SQLite's %S gives whole seconds as text; %f gives seconds with the fraction, as SS.SSS.

Questions about SECOND

Why does EXTRACT(second) return 31.5?

PostgreSQL folds fractional seconds into the seconds field. EXTRACT(milliseconds) returns the same field times 1000 (31500), not just the fraction.

Does Oracle DATE store seconds at all?

Yes, whole seconds only. Sub-second precision needs TIMESTAMP, and EXTRACT(second) on a DATE works only after casting.

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.