Add and Subtract Dates using DATEADD in SQL Server
Problem
Date manipulation is a common scenario when retrieving or storing data in a SQL Server database. There are several functions that are available and in this tip we look at how to use the DATEADD function.
Solution
The DATEADD function simply allows you to add or subtract the specified number of units of time to a specified date/time value.
SQL Server DATEADD() Function
The format of the DATEADD function is as follows:
How to use the DATEADD() Function and Examples
Add 30 days to a date SELECT DATEADD(DD,30,@Date)
Add 3 hours to a date SELECT DATEADD(HOUR,-3,@Date)
Subtract 90 minutes from date SELECT DATEADD(MINUTE,-90,@Date)
Check out the chart to get a list of all options
Date Formats and Units of Time
A thing to note is that the date format can be any date format that SQL Server recognizes such as:
9/1/2011
9/1/2011 12:30
9/1/2011 12:30:999
2011-09-01
2011-09-01 12:30
etc...
Here are the units of time, the SQL Server versions in which they can be used, and abbreviations that can be used instead of the full unit of time name:
The table above reveals that there are some units of time that cannot be used with earlier versions of SQL Server. SQL Server 2008 and later introduced new date/time data types: DATETIME2, TIME, and DATETIMEOFFSET. The MICROSECOND and NANSECOND units of time were introduced as well, but cannot be used in earlier versions of SQL Server. Another thing to keep in mind is that you can't use the seconds unit of time with the DATE data type.
SQL Server DATEADD function examples
For all of these examples, the parameter @Date = "2011-09-23 15:48:39.2370000". We can test the examples as follows:
Example 1
A practical use of DATEADD is to return a user-friendly length of time that has elapsed between two times, like how long it takes for a student to complete an exam.
Below we are also using the DATEDIFF function to find the difference between the start and end time in seconds, then adding the number of seconds to 01/01/1900, which can be represented as a 0.
Example 2
Another use would be when retrieving data based on a period. The procedure could pass in a start date and a number of days to retrieve data.
Next Steps
Keep in mind that the NANOSECOND and MICROSECOND units of time can only be used with SQL Server 2008 and later
Also keep in mind that there is more than one way to execute a query and get the same results. There will be tips in the future that will discuss other options
Read about the DATEADD function
Learn more about the date and time data types available in SQL Server 2008 and later.
For other date formats refer to this tip: Date and Time Conversions Using SQL Server
By: Tim Cullen