DATEDIFF returns the number of units (days, hours, months and so on) between two dates. In SQL Server it takes the unit first, then the start date, then the end date:
DATEDIFF(day, start_date, end_date)
DATEDIFF(day, '2026-03-01', '2026-03-10') returns 9. That's the whole idea, but the details change from one database to the next. MySQL's DATEDIFF takes the dates in the opposite order and only does days. PostgreSQL and SQLite don't have a DATEDIFF function at all. And SQL Server's version counts calendar boundaries rather than elapsed time, so it can say a 20-minute gap is "1 day".
| Database | Days between two dates | Other units |
|---|---|---|
| SQL Server, Azure SQL | DATEDIFF(day, start, end) | DATEDIFF(hour | minute | month | year ..., start, end) |
| MySQL, MariaDB | DATEDIFF(end, start) | TIMESTAMPDIFF(HOUR | MINUTE | MONTH ..., start, end) |
| PostgreSQL | end::date - start::date | EXTRACT(EPOCH FROM end - start) / 3600, AGE(end, start) |
| SQLite | julianday(end) - julianday(start) | (unixepoch(end) - unixepoch(start)) / 3600.0 |
| Snowflake, Redshift | DATEDIFF(day, start, end) | Same function, any unit |
| BigQuery | DATE_DIFF(end, start, DAY) | TIMESTAMP_DIFF(end, start, HOUR) |
| Oracle | end_date - start_date | MONTHS_BETWEEN(end, start); 26ai adds DATEDIFF(unit, start, end) |
Jump to: sample table · SQL Server syntax · boundaries vs elapsed time · exact hours and minutes · months and years · calculate age · negative results and NULL · DATEDIFF_BIG and overflow · MySQL · PostgreSQL · SQLite · Snowflake, BigQuery, Oracle · business days · time between rows · DATEDIFF in WHERE · database table · mistakes · FAQ
Sample table
A help desk is the classic place to measure time between two dates: when was a ticket opened, and how long did it take to close? This tickets table has five tickets, each chosen to show a different trap: one closed the same day, one that crossed midnight after 20 minutes, one that spanned a weekend, one that crossed two month boundaries, and one that is still open.
CREATE TABLE tickets (
id INT PRIMARY KEY,
customer VARCHAR(20),
opened_at TIMESTAMP, -- DATETIME2 in SQL Server, DATETIME in MySQL
closed_at TIMESTAMP
);
INSERT INTO tickets VALUES
(1, 'Ana', '2026-03-02 09:15:00', '2026-03-02 17:40:00'),
(2, 'Ben', '2026-03-02 23:50:00', '2026-03-03 00:10:00'),
(3, 'Chloe', '2026-03-06 16:00:00', '2026-03-09 10:30:00'),
(4, 'Dev', '2026-02-27 11:00:00', '2026-04-01 08:00:00'),
(5, 'Elif', '2026-03-10 08:00:00', NULL);
Every query on this page was run on SQL Server 2022, MySQL 8.0.46, PostgreSQL 16 and SQLite 3.45, plus DuckDB for the Snowflake-style examples. The output is copied from the real results, including the errors. Snowflake, BigQuery and Oracle details come from their documentation (Snowflake DATEDIFF, BigQuery date functions, Oracle DATEDIFF).
DATEDIFF syntax in SQL Server
DATEDIFF(datepart, startdate, enddate)
- datepart is the unit you want back:
year,quarter,month,week,day,hour,minute,second,millisecond,microsecondornanosecond. Short forms such asdd,mmandmialso work, but spell the unit out:mmis month andmiis minute, which is easy to mix up. - startdate and enddate can be
date,datetime,datetime2,datetimeoffset,smalldatetimeortimevalues, or strings that convert to one. - The result is
enddate - startdateas anINT. Put the earlier date first to get a positive number.
Here are days, hours and minutes for every ticket:
SELECT id, customer,
DATEDIFF(day, opened_at, closed_at) AS days,
DATEDIFF(hour, opened_at, closed_at) AS hours,
DATEDIFF(minute, opened_at, closed_at) AS minutes
FROM tickets;
id customer days hours minutes
-- -------- ---- ----- -------
1 Ana 0 8 505
2 Ben 1 1 20
3 Chloe 3 66 3990
4 Dev 33 789 47340
5 Elif NULL NULL NULL
Minutes are right for every row. But look at Ben: his ticket was open for 20 minutes, and DATEDIFF says 1 day and 1 hour. That isn't a bug. It's the most important thing to understand about this function.
The datepart has to be a keyword. Passing it as a string, the way Snowflake and PostgreSQL's date_part allow, fails in SQL Server:
SELECT DATEDIFF('day', '2026-03-01', '2026-03-31');
Msg 1023, Level 15, State 1
Invalid parameter 1 specified for datediff.
DATEDIFF counts boundaries, not elapsed time
SQL Server's DATEDIFF counts how many times the unit's boundary is crossed between the two values. A day boundary is midnight, an hour boundary is the top of the hour, a year boundary is January 1. It ignores everything smaller than the unit you asked for.
SELECT DATEDIFF(year, '2025-12-31', '2026-01-01') AS years,
DATEDIFF(month, '2026-01-31', '2026-02-01') AS months,
DATEDIFF(hour, '2026-03-02 09:59:59', '2026-03-02 10:00:00') AS hours;
years months hours
----- ------ -----
1 1 1
One day apart is "1 year". One second apart is "1 hour". So Ben's ticket, opened at 23:50 and closed at 00:10, crossed one midnight (1 day) and one top-of-the-hour (1 hour), even though only 20 minutes passed. Ana's ticket was open for 8 hours 25 minutes and gets 8 hours, but only because she started at 09:15; start at 09:59 and the same length of time would count 9.
Boundary counting is the right answer when you mean calendar units: "how many calendar days later did this ship?" or "how many month-ends did this invoice span?" It's the wrong answer for durations: "how long was this ticket open?" For durations, measure in a small unit and divide, as in the next section.
The same rule applies to week, which counts Sundays crossed no matter what SET DATEFIRST says:
SELECT DATEDIFF(week, '2026-03-07', '2026-03-08') AS sat_to_sun,
DATEDIFF(week, '2026-03-08', '2026-03-14') AS sun_to_sat;
sat_to_sun sun_to_sat
---------- ----------
1 0
Saturday to Sunday is a "week". Sunday to the next Saturday, six days later, is zero weeks. If you want full weeks, use DATEDIFF(day, start, end) / 7.
Snowflake, Redshift, BigQuery's DATE_DIFF, Oracle's new DATEDIFF and DuckDB's datediff all count boundaries the same way. MySQL's TIMESTAMPDIFF and PostgreSQL's interval math measure elapsed time instead, which is why the same question gives different answers on different databases. The MySQL section shows the two side by side.
Exact hours and minutes between two datetimes
To measure a duration, ask for a unit smaller than the one you want and divide. Minutes are precise enough for most business data; use seconds if you need them. Divide by 60.0, not 60, or SQL Server does integer division and throws away the fraction:
SELECT id, customer,
DATEDIFF(minute, opened_at, closed_at) / 60.0 AS hours_exact,
DATEDIFF(second, opened_at, closed_at) / 3600 AS full_hours,
DATEDIFF(second, opened_at, closed_at) / 86400.0 AS days_exact
FROM tickets
WHERE closed_at IS NOT NULL;
id customer hours_exact full_hours days_exact
-- -------- ----------- ---------- ----------
1 Ana 8.416666 8 .3506944
2 Ben .333333 0 .0138888
3 Chloe 66.500000 66 2.7708333
4 Dev 789.000000 789 32.8750000
Now Ben's ticket is 0.33 hours and 0 full hours, which is what actually happened. Integer division by 3600 is handy here: it truncates, so full_hours is the number of complete hours. Wrap the decimal version in ROUND if you want two decimal places.
Show a duration as hours and minutes
For a report, "8h 25m" reads better than 8.416666. Take the total seconds once, then split it with integer division and the remainder operator %:
SELECT id,
CONCAT(DATEDIFF(second, opened_at, closed_at) / 3600, 'h ',
DATEDIFF(second, opened_at, closed_at) % 3600 / 60, 'm') AS duration
FROM tickets
WHERE closed_at IS NOT NULL;
id duration
-- --------
1 8h 25m
2 0h 20m
3 66h 30m
4 789h 0m
Don't use CONVERT(time, closed_at - opened_at) or FORMAT for this: a time value wraps around after 24 hours, so Chloe's 66.5 hours would display as 18:30.
Months and years between two dates
Months are where boundary counting surprises people most. DATEDIFF(month, ...) only compares the year and month parts, so January 31 to February 1 is one month, and January 1 to January 31 is zero.
Dev's ticket ran from February 27 to April 1. That crosses two month boundaries (March 1 and April 1), but it's only one full month plus a few days:
SELECT DATEDIFF(month, '2026-02-27 11:00', '2026-04-01 08:00') AS boundary_months; -- 2
To count complete months, take the boundary count and subtract one when adding that many months to the start date overshoots the end date:
DECLARE @s date = '2026-01-15', @e date = '2026-02-10';
SELECT DATEDIFF(month, @s, @e) AS boundary_months,
DATEDIFF(month, @s, @e)
- CASE WHEN DATEADD(month, DATEDIFF(month, @s, @e), @s) > @e THEN 1 ELSE 0 END AS full_months;
boundary_months full_months
--------------- -----------
1 0
The same CASE correction works for year, which is exactly how you calculate someone's age.
Month-end dates have one more wrinkle: there's no February 31, so DATEADD(month, 1, '2026-01-31') returns 2026-02-28. By the formula above, January 31 to February 28 counts as one full month. MySQL's TIMESTAMPDIFF disagrees and says zero (shown below). Neither is wrong; decide which rule your business uses and test the month-end cases.
Calculate age in SQL
DATEDIFF(year, birth_date, today) is the most common age bug in SQL. It counts New Years crossed, not birthdays reached, so anyone whose birthday hasn't happened yet this year is one year too old:
SELECT DATEDIFF(year, '2000-12-15', '2026-03-02') AS wrong_age,
DATEDIFF(year, '2000-12-15', '2026-03-02')
- CASE WHEN DATEADD(year, DATEDIFF(year, '2000-12-15', '2026-03-02'), '2000-12-15') > '2026-03-02'
THEN 1 ELSE 0 END AS age;
wrong_age age
--------- ---
26 25
Someone born on December 15, 2000 is 25 on March 2, 2026. In a real query, replace '2026-03-02' with CAST(GETDATE() AS date). Other databases have it easier:
- MySQL:
TIMESTAMPDIFF(YEAR, birth_date, CURDATE())counts complete years, so it returns 25 directly. - PostgreSQL:
EXTRACT(YEAR FROM AGE(CURRENT_DATE, birth_date)), also 25. - SQLite: compare the year, then knock one off if this year's birthday is still ahead:
(strftime('%Y', 'now') - strftime('%Y', birth_date)) - (strftime('%m-%d', 'now') < strftime('%m-%d', birth_date)).
Negative results, same-day dates and NULL
If the end date comes before the start date, DATEDIFF returns a negative number. It doesn't swap them for you:
SELECT DATEDIFF(day, '2026-03-10', '2026-03-01') AS backwards;
backwards
---------
-9
Two values on the same date return 0 for day. If either value is NULL, the result is NULL, which is why Elif's open ticket showed NULL in every column. To measure open tickets up to now, swap in the current time with COALESCE. (The example uses a fixed "now" so the output stays the same; in practice use GETDATE().)
SELECT id, customer,
DATEDIFF(day, opened_at, COALESCE(closed_at, '2026-03-12 12:00:00')) AS days_open
FROM tickets;
id customer days_open
-- -------- ---------
1 Ana 0
2 Ben 1
3 Chloe 3
4 Dev 33
5 Elif 2
An invalid date string is an error, not NULL: DATEDIFF(day, '2026-03-12', '2026-02-30') fails with Conversion failed when converting date and/or time from character string. Write date literals as 'YYYY-MM-DD'; formats like '03/02/2026' depend on the server's language setting.
DATEDIFF_BIG and the overflow error
DATEDIFF returns an INT, which tops out at 2,147,483,647. That's about 68 years in seconds, but only 24.8 days in milliseconds, so small units over long ranges fail:
SELECT DATEDIFF(millisecond, '2026-01-01', '2026-03-01') AS ms;
Msg 535, Level 16, State 1
The datediff function resulted in an overflow. The number of dateparts separating two
date/time instances is too large. Try to use datediff with a less precise datepart.
SQL Server 2016 and later have DATEDIFF_BIG, which is identical but returns a BIGINT:
SELECT DATEDIFF_BIG(millisecond, '2026-01-01', '2026-03-01') AS ms;
ms
----------
5097600000
Also note that sub-second units still count boundaries: from 10:00:00.900 to 10:00:01.100 is 200 milliseconds, but DATEDIFF(second, ...) returns 1.
DATEDIFF and TIMESTAMPDIFF in MySQL
MySQL has two functions, and both differ from SQL Server.
MySQL DATEDIFF: days only, end date first
DATEDIFF(end_date, start_date)
There's no unit argument: it always returns days, it ignores the time of day, and the end date comes first. Swap them and the sign flips:
SELECT DATEDIFF('2026-03-01', '2026-03-10') AS wrong_order,
DATEDIFF('2026-03-10', '2026-03-01') AS right_order;
+-------------+-------------+
| wrong_order | right_order |
+-------------+-------------+
| -9 | 9 |
+-------------+-------------+
Pasting SQL Server code into MySQL fails, because MySQL's version takes two arguments:
SELECT DATEDIFF(day, '2026-03-01', '2026-03-10');
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'DATEDIFF'
Since it only looks at the date part, DATEDIFF(closed_at, opened_at) gives the same calendar-day answers as SQL Server: 0, 1, 3, 33 and NULL for our tickets. Ben's 20-minute ticket is "1 day" here too.
MySQL TIMESTAMPDIFF: any unit, complete units only
TIMESTAMPDIFF(unit, start, end)
This one has SQL Server's argument order, but it counts complete units of elapsed time rather than boundaries:
SELECT id, customer,
TIMESTAMPDIFF(DAY, opened_at, closed_at) AS days,
TIMESTAMPDIFF(HOUR, opened_at, closed_at) AS hours,
TIMESTAMPDIFF(MINUTE, opened_at, closed_at) AS minutes,
TIMESTAMPDIFF(MONTH, opened_at, closed_at) AS months
FROM tickets
WHERE closed_at IS NOT NULL;
+----+----------+------+-------+---------+--------+
| id | customer | days | hours | minutes | months |
+----+----------+------+-------+---------+--------+
| 1 | Ana | 0 | 8 | 505 | 0 |
| 2 | Ben | 0 | 0 | 20 | 0 |
| 3 | Chloe | 2 | 66 | 3990 | 0 |
| 4 | Dev | 32 | 789 | 47340 | 1 |
+----+----------+------+-------+---------+--------+
Compare that with the SQL Server output: Ben is 0 days instead of 1, Chloe is 2 days instead of 3 (2 days 18.5 hours), and Dev is 32 days and 1 month instead of 33 days and 2 months. The boundary examples that all returned 1 in SQL Server return 0 here:
SELECT TIMESTAMPDIFF(YEAR, '2025-12-31', '2026-01-01') AS years,
TIMESTAMPDIFF(MONTH, '2026-01-31', '2026-02-01') AS months,
TIMESTAMPDIFF(HOUR, '2026-03-02 09:59:59', '2026-03-02 10:00:00') AS hours;
+-------+--------+-------+
| years | months | hours |
+-------+--------+-------+
| 0 | 0 | 0 |
+-------+--------+-------+
Month-end dates follow the same rule: TIMESTAMPDIFF(MONTH, '2026-01-31', '2026-02-28') is 0, because February 28 is before "February 31". If you're moving reports from SQL Server to MySQL (or back), these are the numbers that will change.
For a readable duration, TIMEDIFF(closed_at, opened_at) returns 08:25:00, 66:30:00 and so on. It caps at 838:59:59 (about 35 days), though. A two-month gap comes back as 838:59:59 with only a warning (Truncated incorrect time value: '1416:00:00'), so use TIMESTAMPDIFF(MINUTE, ...) for long durations. An invalid date such as '2026-02-30' makes DATEDIFF return NULL with a warning, not an error.
Date difference in PostgreSQL (no DATEDIFF)
PostgreSQL has no DATEDIFF function:
SELECT DATEDIFF('day', opened_at, closed_at) FROM tickets;
ERROR: function datediff(unknown, timestamp without time zone, timestamp without time zone) does not exist
LINE 1: SELECT DATEDIFF('day', opened_at, closed_at) FROM tickets;
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
You don't need one. Subtracting two dates gives an integer number of days, and subtracting two timestamps gives an interval:
SELECT id, customer,
closed_at - opened_at AS elapsed,
closed_at::date - opened_at::date AS days
FROM tickets;
id | customer | elapsed | days
----+----------+------------------+------
1 | Ana | 08:25:00 | 0
2 | Ben | 00:20:00 | 1
3 | Chloe | 2 days 18:30:00 | 3
4 | Dev | 32 days 21:00:00 | 33
5 | Elif | |
Casting both sides to date first gives calendar days, the same as SQL Server's DATEDIFF(day, ...). The elapsed interval is the true duration.
Hours and minutes in PostgreSQL
To turn an interval into a number, extract the total seconds with EPOCH and divide:
SELECT id, customer,
ROUND(EXTRACT(EPOCH FROM closed_at - opened_at) / 3600, 2) AS hours,
EXTRACT(EPOCH FROM closed_at - opened_at)::int / 60 AS minutes
FROM tickets
WHERE closed_at IS NOT NULL;
id | customer | hours | minutes
----+----------+--------+---------
1 | Ana | 8.42 | 505
2 | Ben | 0.33 | 20
3 | Chloe | 66.50 | 3990
4 | Dev | 789.00 | 47340
EXTRACT(DAY FROM closed_at - opened_at) returns complete days of the interval (0, 0, 2 and 32 here). Be careful with AGE(), though: it returns years, months and days, so EXTRACT(DAY FROM AGE('2026-04-01 08:00', '2026-02-27 11:00')) is 1, the "1 day" in "1 mon 1 day 21:00:00", not 32.
Months and years in PostgreSQL
AGE(end, start) is the tool for calendar months and years. It counts complete units, like MySQL:
SELECT AGE(DATE '2026-03-02', DATE '2000-12-15') AS age,
EXTRACT(YEAR FROM AGE(DATE '2026-03-02', DATE '2000-12-15')) AS years;
age | years
-------------------------+-------
25 years 2 mons 18 days | 25
Total complete months are EXTRACT(YEAR FROM AGE(e, s)) * 12 + EXTRACT(MONTH FROM AGE(e, s)), which is 1 for Dev's ticket. If you want SQL Server's boundary count instead (2 for Dev), compare the year and month parts directly:
(EXTRACT(YEAR FROM e) - EXTRACT(YEAR FROM s)) * 12 + EXTRACT(MONTH FROM e) - EXTRACT(MONTH FROM s)
Date difference in SQLite
SQLite has no date type and no DATEDIFF (Parse error: no such function: DATEDIFF). Dates are stored as text, so convert them to numbers first. julianday() returns fractional days and unixepoch() (SQLite 3.38+) returns whole seconds:
SELECT id, customer,
julianday(closed_at) - julianday(opened_at) AS days_exact,
julianday(date(closed_at)) - julianday(date(opened_at)) AS days,
(unixepoch(closed_at) - unixepoch(opened_at)) / 3600.0 AS hours,
(unixepoch(closed_at) - unixepoch(opened_at)) / 60 AS minutes
FROM tickets
WHERE closed_at IS NOT NULL;
id customer days_exact days hours minutes
-- -------- ------------------ ---- ----------------- -------
1 Ana 0.350694444496185 0.0 8.41666666666667 505
2 Ben 0.0138888889923692 1.0 0.333333333333333 20
3 Chloe 2.77083333348855 3.0 66.5 3990
4 Dev 32.875 33.0 789.0 47340
Wrapping each side in date() gives calendar days, like SQL Server. Without it you get the exact duration in days. Notice the noise at the end of 0.350694444496185: julianday() is a floating-point number, so for hours, minutes and seconds unixepoch() is the cleaner choice. On SQLite older than 3.38, use strftime('%s', closed_at) instead.
Two SQLite traps worth knowing:
- Subtracting the text directly:
'2026-03-10' - '2026-03-01'returns0. SQLite turns each string into the number at its start (2026) and subtracts those. - Bad dates don't fail:
julianday('3/1/2026')isNULL, andjulianday('2026-02-30')quietly becomes March 2. Store dates as'YYYY-MM-DD'or'YYYY-MM-DD HH:MM:SS'and validate on the way in. The SQLite date and time guide covers the formats.
Months are year and month parts again: (strftime('%Y', e) - strftime('%Y', s)) * 12 + strftime('%m', e) - strftime('%m', s) gives the boundary count (2 for Dev).
Snowflake, Redshift, BigQuery and Oracle
Snowflake and Redshift use SQL Server's form, DATEDIFF(unit, start, end), and the same boundary counting. Snowflake's documentation gives December 31, 2015 to January 1, 2016 as 1 year, 1 month and 1 day. The unit can be quoted or not ('day' or day), and WEEK follows the WEEK_START session parameter. Snowflake also lets you subtract two dates (end_date - start_date) to get days.
DuckDB has both models, which makes the difference easy to see. datediff (alias date_diff) counts boundaries like Snowflake; date_sub counts complete units like MySQL:
SELECT id, customer,
datediff('day', opened_at, closed_at) AS days,
datediff('hour', opened_at, closed_at) AS hours,
date_sub('day', opened_at, closed_at) AS full_days,
date_sub('hour', opened_at, closed_at) AS full_hours
FROM tickets
WHERE closed_at IS NOT NULL;
┌───────┬──────────┬───────┬───────┬───────────┬────────────┐
│ id │ customer │ days │ hours │ full_days │ full_hours │
├───────┼──────────┼───────┼───────┼───────────┼────────────┤
│ 1 │ Ana │ 0 │ 8 │ 0 │ 8 │
│ 2 │ Ben │ 1 │ 1 │ 0 │ 0 │
│ 3 │ Chloe │ 3 │ 66 │ 2 │ 66 │
│ 4 │ Dev │ 33 │ 789 │ 32 │ 789 │
└───────┴──────────┴───────┴───────┴───────────┴────────────┘
BigQuery puts the end date first and the unit last: DATE_DIFF(end_date, start_date, DAY), with DATETIME_DIFF and TIMESTAMP_DIFF for the other types. It counts boundaries, and has extra week units: WEEK (Sunday start), WEEK(MONDAY) and ISOWEEK.
Oracle traditionally has no DATEDIFF. Subtracting two DATE values returns days as a decimal (multiply by 24 for hours), subtracting TIMESTAMPs returns an interval, and MONTHS_BETWEEN(end, start) returns fractional months. The Oracle AI Database 26ai documentation adds DATEDIFF(unit, start, end) (synonym TIMESTAMPDIFF) with SQL Server-style boundary counting, so check your version before using it.
Business days between two dates (excluding weekends)
None of these functions knows about weekends. Chloe's ticket ran from Friday afternoon to Monday morning: 3 calendar days, but only 1 working day.
In SQL Server, the week boundary is always Sunday, so DATEDIFF(week, ...) counts the weekends crossed. Subtract two days for each:
SELECT id, customer,
DATEDIFF(day, opened_at, closed_at) AS calendar_days,
DATEDIFF(day, opened_at, closed_at)
- 2 * DATEDIFF(week, opened_at, closed_at) AS business_days
FROM tickets
WHERE closed_at IS NOT NULL;
id customer calendar_days business_days
-- -------- ------------- -------------
1 Ana 0 0
2 Ben 1 1
3 Chloe 3 1
4 Dev 33 23
This shortcut is only correct when both dates fall on weekdays. A start or end on a Saturday or Sunday throws it off by one, and it doesn't know about holidays.
The approach that always works is to list the days and count the weekdays. In PostgreSQL, generate_series does the listing:
SELECT id, customer,
(SELECT COUNT(*)
FROM generate_series(opened_at::date + 1, closed_at::date, interval '1 day') AS d
WHERE EXTRACT(ISODOW FROM d) < 6) AS business_days
FROM tickets
WHERE closed_at IS NOT NULL;
id | customer | business_days
----+----------+---------------
1 | Ana | 0
2 | Ben | 1
3 | Chloe | 1
4 | Dev | 23
Both count the weekdays after the start date, up to and including the end date. For holidays, the standard answer is a calendar table: one row per date with an is_business_day flag. Then the business days between two dates is a COUNT(*) over a BETWEEN range, and it works the same in every database.
Time between rows: days since the previous order
A common analysis question is "how long between one event and the next?": days between a customer's orders, or hours between tickets. Combine DATEDIFF with the LAG window function, which reads a value from the previous row:
SELECT id, customer, opened_at,
DATEDIFF(hour, LAG(opened_at) OVER (ORDER BY opened_at), opened_at) AS hours_since_previous
FROM tickets
ORDER BY opened_at;
id customer opened_at hours_since_previous
-- -------- ------------------- --------------------
4 Dev 2026-02-27 11:00:00 NULL
1 Ana 2026-03-02 09:15:00 70
2 Ben 2026-03-02 23:50:00 14
3 Chloe 2026-03-06 16:00:00 89
5 Elif 2026-03-10 08:00:00 88
The first row has no previous row, so it's NULL. Add PARTITION BY customer_id inside OVER to measure the gap per customer. To get an average, wrap it in a subquery or CTE and use AVG(); to compare groups, add GROUP BY.
DATEDIFF in WHERE: keep the column bare
"Tickets opened in the last 7 days" is often written like this:
SELECT id, customer
FROM tickets
WHERE DATEDIFF(day, opened_at, '2026-03-12') <= 7;
It returns the right rows (Chloe and Elif), but it has to run DATEDIFF on every row in the table, so an index on opened_at can't be used. Do the date math on the constant instead and compare the column directly:
SELECT id, customer
FROM tickets
WHERE opened_at >= DATEADD(day, -7, '2026-03-12');
Same result, and now the database can seek straight to the matching rows. The equivalents are opened_at >= NOW() - INTERVAL 7 DAY in MySQL, opened_at >= NOW() - INTERVAL '7 days' in PostgreSQL and opened_at >= datetime('now', '-7 days') in SQLite. The BETWEEN guide covers date ranges and the end-of-day trap in more detail.
The two filters aren't exactly the same: DATEDIFF(day, ...) <= 7 counts calendar days, so it includes everything since midnight seven days ago, while DATEADD on a timestamp goes back exactly 7 × 24 hours. Use DATEADD(day, -7, CAST(GETDATE() AS date)) if you want whole days.
Date difference in each database
| SQL Server | MySQL | PostgreSQL | SQLite | Snowflake | |
|---|---|---|---|---|---|
| Function | DATEDIFF(unit, s, e) | DATEDIFF(e, s), TIMESTAMPDIFF(unit, s, e) | e - s, AGE(e, s) | julianday(), unixepoch() | DATEDIFF(unit, s, e) |
| Argument order | Start, end | End, start (DATEDIFF); start, end (TIMESTAMPDIFF) | End minus start | End minus start | Start, end |
| Counts | Boundaries | Calendar days (DATEDIFF); complete units (TIMESTAMPDIFF) | Exact interval | Exact (fractional days or seconds) | Boundaries |
| 23:50 to 00:10, in days | 1 | 1 / 0 | 0 (interval 00:20:00) | 0.0139 | 1 |
| Dec 31 to Jan 1, in years | 1 | 0 | 0 | n/a | 1 |
| Exact hours | DATEDIFF(minute, s, e) / 60.0 | TIMESTAMPDIFF(MINUTE, s, e) / 60 | EXTRACT(EPOCH FROM e - s) / 3600 | (unixepoch(e) - unixepoch(s)) / 3600.0 | DATEDIFF(minute, s, e) / 60 |
| Age in years | DATEDIFF(year, ...) minus 1 if birthday not reached | TIMESTAMPDIFF(YEAR, b, CURDATE()) | EXTRACT(YEAR FROM AGE(b)) | strftime year math | DATEDIFF(year, ...) minus 1 if birthday not reached |
| Large values | DATEDIFF_BIG | BIGINT already | n/a | n/a | BIGINT already |
For the matching "add an interval" functions, see adding days in T-SQL and adding days in MySQL.
Common DATEDIFF mistakes
- Using
DATEDIFF(day | hour | year, ...)as a duration in SQL Server: it counts boundaries, so 20 minutes across midnight is 1 day. Measure in minutes or seconds and divide. - Calculating age with
DATEDIFF(year, ...): it's a year too high until the birthday. Subtract 1 when the birthday hasn't happened yet this year. - Swapping the arguments in MySQL: MySQL's
DATEDIFFis end first, SQL Server's is start first. A negative result is the giveaway. - Dividing by
60instead of60.0:DATEDIFFreturns an integer, and integer division in SQL Server (and in PostgreSQL and SQLite with integer values) drops the fraction, so 505 minutes becomes 8 hours. - Expecting the same answer on two databases: SQL Server and Snowflake count boundaries; MySQL
TIMESTAMPDIFFand PostgreSQLAGEcount complete units. Test month and year differences when you migrate. - Calling
DATEDIFFin PostgreSQL or SQLite: it doesn't exist. Subtract dates in PostgreSQL; usejulianday()orunixepoch()in SQLite. - Subtracting date strings in SQLite:
'2026-03-10' - '2026-03-01'is 0. - Millisecond differences over long ranges: overflow error in SQL Server after about 24 days. Use
DATEDIFF_BIG. - Wrapping an indexed column in
DATEDIFFinWHERE: forces a full scan. Move the date math to the other side withDATEADD. - Forgetting
NULLend dates: open records returnNULL. UseCOALESCE(end_date, GETDATE())if you want "so far".
FAQ
What does DATEDIFF do in SQL?
It returns the difference between two dates or times as a whole number of the unit you choose, such as days, hours or months. In SQL Server the syntax is DATEDIFF(unit, start_date, end_date), and the result is positive when the end date is later.
How do I get the number of days between two dates in SQL?
DATEDIFF(day, start, end) in SQL Server, Snowflake and Redshift; DATEDIFF(end, start) in MySQL; end::date - start::date in PostgreSQL; julianday(end) - julianday(start) in SQLite; DATE_DIFF(end, start, DAY) in BigQuery; and end - start in Oracle.
Why does DATEDIFF return 1 day for times only minutes apart?
SQL Server's DATEDIFF counts how many unit boundaries are crossed, and for day the boundary is midnight. 23:50 to 00:10 crosses one midnight, so it's 1 day. For elapsed time, use DATEDIFF(minute, start, end) / 1440.0.
How do I calculate the difference in hours and minutes?
Get the total minutes (or seconds) and split them: DATEDIFF(minute, s, e) / 60 is the hours and DATEDIFF(minute, s, e) % 60 is the remaining minutes. For a decimal, divide by 60.0. In MySQL use TIMESTAMPDIFF(MINUTE, s, e); in PostgreSQL EXTRACT(EPOCH FROM e - s) / 60.
Does PostgreSQL have DATEDIFF?
No. Subtract the values instead: date - date gives days as an integer and timestamp - timestamp gives an interval. Use EXTRACT(EPOCH FROM ...) to turn an interval into seconds, and AGE() for years and months.
What is the difference between DATEDIFF and TIMESTAMPDIFF in MySQL?
DATEDIFF(end, start) only returns calendar days and ignores times. TIMESTAMPDIFF(unit, start, end) takes a unit (SECOND to YEAR) and returns complete units of elapsed time. Note that the argument orders are opposite.
Is DATEDIFF inclusive?
No. DATEDIFF(day, '2026-03-01', '2026-03-10') is 9, not 10: it counts the gaps between the dates, not the dates themselves. If you want to count both the first and the last day, as in "a hotel stay from the 1st to the 10th is 10 days", add 1.
How do I calculate the number of months between two dates?
DATEDIFF(month, s, e) in SQL Server counts month boundaries, so January 31 to February 1 is 1. For complete months, use TIMESTAMPDIFF(MONTH, s, e) in MySQL, AGE() in PostgreSQL, or subtract 1 from the SQL Server result when DATEADD(month, result, s) is after e.
Practice with real queries
Date math clicks once you run it against real data. The free interactive lessons start with SELECT and WHERE, then cover GROUP BY, NULL and joins. They run in your browser on a real SQLite database with no signup. After that, try the SQL practice problems and keep the SQL cheat sheet open. Related guides: BETWEEN for date ranges, comparing dates, CAST for turning text into dates, and window functions for time between rows.