// dates & times reference

SQL timestamp minus timestamp

Direct subtraction of two timestamps yields a duration on PostgreSQL and Oracle. SQL Server and MySQL accept the minus sign but return something that is not a duration.

Category
Dates & times
Returns
interval (PG, Oracle) / number (Oracle DATE)
In this category
77 of 121

Syntax

ts1 - ts2

Engine support

EngineSupportNotes
SQL Server Different name or syntax DATEDIFF(unit, a, b) or DATEDIFF_BIG; no interval type
PostgreSQL Yes Supported under this name.
MySQL Different name or syntax TIMESTAMPDIFF(unit, a, b)
SQLite Different name or syntax JULIANDAY(a) - JULIANDAY(b)
Oracle Yes Supported under this name.

Examples

PostgreSQL

SELECT TIMESTAMPTZ '2026-08-01 12:00+00' - TIMESTAMPTZ '2026-08-01 09:00+00';  -- 03:00:00

Oracle

SELECT TIMESTAMP '2026-08-01 12:00:00' - TIMESTAMP '2026-08-01 09:00:00' FROM dual;  -- +000000000 03:00:00.000000000

SQLite

SELECT JULIANDAY(ended) - JULIANDAY(started) AS days FROM jobs;

Good to know

  • PostgreSQL returns days and time, never months: TIMESTAMP '2026-09-03 03:00' - TIMESTAMP '2026-08-01' is 33 days 03:00:00. Use AGE for a years-months-days answer and EXTRACT(EPOCH FROM ...) for seconds.
  • Oracle DATE subtraction gives a number of days with a fraction (1.125 = 27 hours); TIMESTAMP subtraction gives INTERVAL DAY TO SECOND instead. Same operator, two behaviours.
  • On PostgreSQL, timestamptz - timestamptz measures real elapsed time: midnight to midnight across the 2026-03-08 spring-forward in America/New_York is 23:00:00, while timestamp - timestamp on the same wall times reports 1 day.
  • SQL Server's datetime - datetime returns a datetime counted from 1900-01-01 (14:30 minus 12:00 is 1900-01-01 02:30:00), and MySQL's DATETIME - DATETIME subtracts the values as YYYYMMDDhhmmss numbers (14:30 minus 12:00 is 23000). Use DATEDIFF or TIMESTAMPDIFF instead.

Questions about TIMESTAMP - TIMESTAMP

How do I turn a PostgreSQL interval into hours?

EXTRACT(EPOCH FROM iv) / 3600. EXTRACT(HOUR FROM iv) only reads the interval's hour field and ignores days and months.

What does SQL Server give instead?

An interval type does not exist; pick the unit up front with DATEDIFF or compute seconds and divide.

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.