Dates in SQL Server: DATEADD, DATEDIFF and DATEPART
SQL Server date functions take the unit as a plain word: day, month, year.
Dialects · SQL Server
Free. No sign up. Your progress stays in this browser.
What you will learn
Three functions cover most date work in SQL Server.
The order of arguments matters, especially in DATEDIFF.
The basics
SQL Server has its own date functions. The unit is written as a plain word without quotes.
SELECT invoice_id,
DATEADD(day, 30, due_date) AS reminder_date,
DATEDIFF(day, due_date, '2026-07-01') AS days_since_due,
DATEPART(month, due_date) AS month_no
FROM invoicesDATEADD(unit, number, date) moves a date. DATEDIFF(unit, start, end) counts the unit boundaries between two dates, start first. YEAR(), MONTH() and DAY() are shortcuts.
SQL Server does not accept a column alias in GROUP BY, so repeat the expression there. GETDATE() returns the current date and time.
Worked examples
Example 1
A reminder 30 days after the due date, and days since it.
SELECT invoice_id,
DATEADD(day, 30, due_date) AS reminder_date,
DATEDIFF(day, due_date, '2026-07-01') AS days_since_due
FROM invoicesDATEDIFF counts from the first date to the second.
Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.
Try a taskCommon mistakes
- Swapping the dates in DATEDIFF and getting negative numbers.
- Putting the unit in quotes.
- Expecting DATEDIFF(month, ...) to count full months. It counts month boundaries.
Where you will use it at work
- Finance: days overdue.
- HR: tenure in years.
- Support: hours to first reply.
Questions people ask
How do I get today’s date?
GETDATE() returns the date and time; CAST(GETDATE() AS date) the date only.
How do I group by month?
GROUP BY YEAR(d), MONTH(d), or by DATEFROMPARTS(YEAR(d), MONTH(d), 1).
Is there DATE_TRUNC?
SQL Server 2022 adds DATETRUNC.
Ready to write it yourself?
Practice Dates in SQL ServerRelated guides
SQL Practice is independent and not affiliated with the maker of this database. The exercises run on SQLite in your browser and imitate this dialect’s syntax for practice.