DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • Reconciling Privacy Preferences Across Two Datastores With Snowflake and Airflow
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Apache Phoenix With Variable-Length Encoded Data

Trending

  • Jakarta EE 12: Entering the Data Age of Enterprise Java
  • AI Paradigm Shift: Analytics Without SQL
  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  • From Indicators to Insights: Automating IOC Enrichment Using Python and Threat Feeds
  1. DZone
  2. Data Engineering
  3. Data
  4. Dates and Times in SQL Server: DATEADD()

Dates and Times in SQL Server: DATEADD()

We almost always have to work with dates when it comes to databases. Look at T-SQL's DATEADD() function and how it can help make your life easier.

By 
Randolph West user avatar
Randolph West
·
Updated Nov. 20, 18 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
10.4K Views

Join the DZone community and get the full member experience.

Join For Free

We are now in the home stretch of the long-running series about dates and times in SQL Server and Azure SQL Database.

This week we look at one of my favorite T-SQL functions when it comes to dates and times: DATEADD().

Syntax

As with similar functions, DATEADD can do arithmetic on dates as well as times. The syntax is straightforward:

DATEADD (datepart, number, date)

The number portion must be an integer, and it must be within the acceptable range of values for the date part.

The datepart portion must be one of the following date parts (which we’ve seen in previous posts):

datepart Abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns

Although DATEADD supports abbreviations as shown in the preceding table, we should make every effort to use the full expression to ensure clarity in our code. SQL Server does not run any faster if we use abbreviations.

Also keep in mind that although we can add or subtract nanoseconds with DATEADD, the smallest granularity for a DATETIME2 data type is 100 nanoseconds, so rounding needs to be taken into account.

Return Type

DATEADD will return a result using the data type that was used in the date parameter. For example, if we use a literal string representing a date in YYYYMMDD format, the return type will be a DATETIME value, because literal strings are implicitly converted to DATETIME.

SELECT DATEADD(DAY, 1, '20181031')
-- returns the DATETIME value '2018-11-01 00:00:00.000'

However, if we use a DATETIME2 input value, the result will be a DATETIME2 value.

SELECT DATEADD(NANOSECOND, 100, CAST('20181031' AS DATETIME2))
-- returns the DATETIME2 value '2018-10-31 00:00:00.0000001'

Addition and Subtraction

We saw previously that DATEADD can be used for addition and subtraction, which makes it easy to calculate values backwards as well as forwards. Let’s assume we need to calculate a point in time that was 100 days ago. If we use today as our starting point, it would look as follows:

DECLARE @dt DATETIME2 = SYSUTCDATETIME();
SELECT @dt AS [TimeNow], DATEADD(DAY, -100, @dt) AS [TimeThen];

Notice the use of the negative sign in the number portion. The results would look as follows:

TimeNow: 2018-10-31 09:17:21.7866500
TimeThen: 2018-07-23 09:17:21.7866500

Arithmetic on Months

One final thought on this function. When adding or subtracting months, take care with months that do not contain 31 days. For example, let’s add a month to the end of February 2018:

SELECT DATEADD(MONTH, 1, '20180228')
-- returns the DATETIME value '20180328'

However, if we add one, two, or three months to the end of January 2018, we would see different results:

SELECT DATEADD(MONTH, 1, '20180131');
-- returns the DATETIME value '20180228'

SELECT DATEADD(MONTH, 2, '20180131');
-- returns the DATETIME value '20180331'

SELECT DATEADD(MONTH, 3, '20180131');
-- returns the DATETIME value '20180430'

DATEADD is a very useful system function in T-SQL for adding and subtracting values from a date and time, which I make extensive use of. As long as we keep in mind its quirks around data types and length of months, it can be extremely powerful.

Feel free to share your tips and tricks in the comments below.

sql Data Types

Published at DZone with permission of Randolph West. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • Reconciling Privacy Preferences Across Two Datastores With Snowflake and Airflow
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Apache Phoenix With Variable-Length Encoded Data

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook