// dates & times reference

SQL SEC_TO_TIME function

Converts a second count to a TIME value and back, the tidiest way to aggregate durations in MySQL.

類別
Dates & times
Returns
time / integer
In this category
82 of 121

語法

SEC_TO_TIME(seconds)
TIME_TO_SEC(time_value)

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

引擎支援

引擎Support備註
SQL Server Not built in no direct pair; DATEADD(SECOND, ...) and DATEDIFF(SECOND, '00:00:00', t)
PostgreSQL Different name or syntax make_interval(secs => n) and EXTRACT(EPOCH FROM t)
MySQL 是 Supported under this name.
SQLite Not built in No built-in equivalent.
Oracle Different name or syntax NUMTODSINTERVAL(n, 'SECOND') and EXTRACT(SECOND FROM ...) or cast math

範例

MySQL

SELECT SEC_TO_TIME(5400);  -- 01:30:00

MySQL

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(duration))) FROM shifts;

PostgreSQL

SELECT make_interval(secs => 5400);  -- 01:30:00

小知識

  • TIME_TO_SEC works on clock times and durations alike: TIME_TO_SEC('01:30:00') is 5400, TIME_TO_SEC('-01:30:00') is -5400.
  • SEC_TO_TIME of values beyond TIME's range (838:59:59) clips; aggregate in seconds, convert only for display.
  • PostgreSQL's EXTRACT(EPOCH FROM TIME '01:30:00') gives 5400 the same way; Oracle needs interval casts and EXTRACT part by part.

Questions about SEC_TO_TIME / TIME_TO_SEC

How do I sum a TIME column?

SUM(TIME_TO_SEC(t)), then SEC_TO_TIME on the total. SUM on a TIME column adds the values as hhmmss numbers: 01:30:00 plus 01:45:00 sums to 27500, not 03:15:00.

What is the SQL Server pattern?

Keep everything in seconds: DATEDIFF(SECOND, '00:00:00', t) to integers, SUM, then DATEADD(SECOND, total, '00:00:00') for display.

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: PostgreSQL, MySQL, 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.