SQL reference

Days between two dates in SQL (DATEDIFF)

In Excel, you'd reach for
fx=B2-A2, =DATEDIF(A2, B2, "d"), =NETWORKDAYS()

Time between two dates is everywhere in business data: days to close a deal, hours to resolve a ticket, days from signup to first purchase. Every database can do it; each spells it differently.

The example uses SQLite (what runs on this page): julianday() turns a date into a day number, so subtracting gives days. Multiply by 24 for hours.

Syntax

-- SQLite (this site)
julianday(end) - julianday(start)
-- SQL Server
DATEDIFF(day, start, end)
Try itEdit the query, then Run
idopened_atclosed_atdays_openhours_open
12026-01-18 16:002026-01-18 21:480.245.8
22026-01-19 20:002026-01-22 14:042.7566.1
32026-01-28 03:002026-01-30 17:452.6162.8
42026-01-31 11:002026-02-02 10:53247.9
52026-01-31 22:002026-02-03 00:112.0950.2
62026-02-01 00:002026-02-02 01:001.0425
72026-02-01 03:002026-02-02 01:560.9622.9
82026-02-07 08:002026-02-07 17:070.389.1
92026-02-07 12:002026-02-08 02:470.6214.8
102026-02-07 19:002026-02-08 06:410.4911.7

10 rows

In other databases

  • SQL Server: DATEDIFF(day, start, end); swap day for hour, month and so on. It counts boundaries crossed, so Dec 31 to Jan 1 is 1 year.
  • MySQL: DATEDIFF(end, start) returns days (note the order); TIMESTAMPDIFF(HOUR, start, end) for other units
  • Postgres: end_date - start_date gives days for dates; for timestamps use EXTRACT(EPOCH FROM end - start) / 3600 for hours
  • BigQuery: DATE_DIFF(end, start, DAY), TIMESTAMP_DIFF(end, start, HOUR)
  • Snowflake: DATEDIFF(day, start, end)

Your turn

Average days from signup_date to a subscription's started_at, as avg_days_to_pay, rounded to 1 decimal.

This page on one card

Days between two dates in SQL (DATEDIFF): the Excel way (=B2-A2) and the SQL query, side by side
Days between two dates in SQL (DATEDIFF), on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows