solving sql server problems for millions of dbas and developers since 2006



SQL Server DBA Tips SQL Server Developer Tips SQL Server Business Intelligence Tips SQL Server Career Tips SQL Server Tip Categories SQL Server Tutorials SQL Server Webcasts SQL Server Whitepapers SQL Server Tools SQL Server Questions and Answers MSSQLTips Authors About MSSQLTips SQL Server User Groups MSSLQTips Giveaways MSSQLTips Advertising Options

MSSQLTips Facebook Page MSSQLTips LinkedIn Page MSSQLTips RSS Feed MSSQLTips Twitter Page MSSQLTips Google+ Page

SQL Product Highlight

Devart - dbForge SQL Complete

dbForge SQL Complete is a code autocomplete tool for SQL Server Management Studio and Visual Studio. Free and advanced paid editions of this useful add-in offer powerful autocompletion and formatting of T-SQL code that replaces native Microsoft T-SQL Intellisense.

Learn more!








Add and Subtract Dates using DATEADD in SQL Server

By: | Read Comments | Print

Tim has been working in the IT industry since 2003 and currently works as a SQL Server Reports Developer.

Related Tips: 1 | 2 | 3 | 4 | 5 | 6 | More

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.

The format of the DATEADD function is as follows:

DATEADD(<Unit of time>, <Units>, <Date>)

-- to add 5 days to September 1, 2011 the function would be
DATEADD(DAY, 5, '9/1/2011')

-- to subtract 5 months from September 1, 2011 the function would be
DATEADD(MONTH, -5, '9/1/2011')

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:

Units of Time Available in SQL Server
Unit of time 2000/2005 2008/R2 Abbreviations
NANOSECOND No Yes ns
MICROSECOND No Yes mcs
MILLISECOND Yes Yes ms
SECOND Yes Yes ss, s
MINUTE Yes Yes mi, n
HOUR Yes Yes hh
WEEKDAY Yes Yes dw, w
WEEK Yes Yes wk, ww
DAY Yes Yes dd, d
DAYOFYEAR Yes Yes dy, y
MONTH Yes Yes mm, m
QUARTER Yes Yes qq, q
YEAR Yes Yes yy, yyyy

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.


Below are examples of using the DATEADD function. 
For all of these examples, the parameter @Date = "2011-09-23 15:48:39.2370000".

Examples of Using the DATEADD Function
Unit of time Query Result
NANOSECOND SELECT DATEADD(NANOSECOND,150000,@Date) 2011-09-23 15:48:39.2371500

MICROSECOND SELECT DATEADD(MICROSECOND,150000,@Date) 2011-09-23 15:48:39.3870000

MILLISECOND SELECT DATEADD(MILLISECOND,1500,@Date) 2011-09-23 15:48:39.2385000

SECOND SELECT DATEADD(SECOND,1500,@Date) 2011-09-23 16:13:39

MINUTE SELECT DATEADD(MINUTE,15,@Date) 2011-09-23 16:03:39

HOUR SELECT DATEADD(HOUR,-3,@Date) 2011-09-23 12:48:39

WEEKDAY SELECT DATEADD(WEEKDAY,-2,@Date) 2011-09-21 15:48:39

WEEK SELECT DATEADD(WEEK,4,@Date) 2011-10-21 15:48:39

DAY SELECT DATEADD(DD,4,@Date) 2011-09-27 15:48:39

DAYOFYEAR SELECT DATEADD(DY,14,@Date) 2011-10-07 15:48:39

MONTH SELECT DATEADD(MM,-4,@Date) 2011-05-23 15:48:39

QUARTER SELECT DATEADD(Q,-2,@Date) 2011-03-23 15:48:39

YEAR
SELECT DATEADD(YYYY,-5,@Date) 2006-09-23 15:48:39

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.

DECLARE @StartTime DATETIME = '2011-09-23 15:00:00'
       ,@EndTime   DATETIME = '2011-09-23 17:54:02'
SELECT CONVERT(VARCHAR(8), DATEADD(SECOND, DATEDIFF(SECOND,@StartTime, @EndTime),0), 108) as ElapsedTime

-- the output would be 02:54:02

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.

DECLARE @StartDate DATETIME = '2005-07-01'

DECLARE @Units INT = 7

SELECT * FROM AdventureWorks2008R2.Production.WorkOrder
WHERE StartDate BETWEEN @StartDate AND DATEADD(DAY, @Units, @StartDate)

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
  • For other date formats refer to this tip: Date and Time Conversions Using SQL Server


Related Tips: 1 | 2 | 3 | 4 | 5 | 6 | More | Become a paid author


Last Update: 9/30/2011

Share: Share 






Comments and Feedback:


Post a Comment or Question

Keep it clean and stay on the subject or we may delete your comment.
Your email address is not published. Required fields are marked with an asterisk (*)

*Name   *Email   Notify for updates
Comments
*Enter Code refresh code


 
Sponsor Information
"SQL doctor is the best SQL product on the market, by far. All of Idera's tools are great, but this is the icing on the cake!"

The 10 tools in the SQL Developer Bundle cut the time spent in dull and tedious tasks. Learn more.

What grade do you think your SQL Servers get? Find out with Edgewood's SQL Server Health Check starting at $995.

Get SQL Server Tips Straight from Kevin Kline.

Join the over million SQL Server Professionals who get their issues resolved daily.

The SQL Server Security THREAT - It’s Closer Than You Think


Copyright (c) 2006-2012 Edgewood Solutions, LLC All rights reserved
privacy | disclaimer | copyright | advertise | about
authors | contribute | feedback | giveaways | user groups
Some names and products listed are the registered trademarks of their respective owners.


Edgewood Solutions LLC | MSSharePointTips.com | MSSQLTips.com