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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Goose Migrations for Smooth Database Changes
  • Top 5 Key Features of Apache Iceberg for Modern Data Lakes
  • Workarounds for Oracle Restrictions on the Size of Expression Lists
  • SQL Server to Postgres Database Migration

Trending

  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • A Modern Stack for Building Scalable Systems
  • Performance Optimization Techniques for Snowflake on AWS
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  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.0K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Goose Migrations for Smooth Database Changes
  • Top 5 Key Features of Apache Iceberg for Modern Data Lakes
  • Workarounds for Oracle Restrictions on the Size of Expression Lists
  • SQL Server to Postgres Database Migration

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!