SQL Server DATEADD() Function

The DATEADD() function is a function in SQL Server used to add or subtract a specified time interval from a date. It is commonly used in queries to calculate dates and can add time intervals such as years, months, days, hours, and minutes.

Syntax

DATEADD(datepart, number, date)

Parameters:

  • datepart: represents the time interval to be added and can be one of the following values:
    • year: year
    • quarter: quarter
    • month: month
    • dayofyear: day of the year
    • day: day
    • week: week
    • weekday: weekday
    • hour: hour
    • minute: minute
    • second: second
    • millisecond: millisecond
  • number: represents the number of the time interval to be added
  • date: represents the date to which the time interval is to be added

Usage

The DATEADD() function is very useful for date calculations in queries, for example:

  • Calculate a date a certain number of days from another date
  • Calculate a date a certain number of months from another date
  • Calculate a date a certain number of years from another date
  • Calculate a date a certain number of hours from another date
  • Calculate a date a certain number of minutes from another date

Examples

Example 1: Calculate a date a certain number of days from another date

Suppose we want to calculate the date 7 days after March 11, 2023. We can use the following SQL statement:

SELECT DATEADD(day, 7, '2023-03-11') AS Result;

The result of the query is:

Result
2023-03-18

Example 2: Calculate a date a certain number of months from another date

Suppose we want to calculate the date 3 months after March 11, 2023. We can use the following SQL statement:

SELECT DATEADD(month, 3, '2023-03-11') AS Result;

The result of the query is:

Result
2023-06-11

Conclusion

The DATEADD() function is one of the most commonly used date functions in SQL Server and is very useful for date calculations. In practical applications, you can use the DATEADD() function with different time intervals based on specific needs.