DEV Community

Cover image for Manipulating Dates with SQL Server
Nathalia Friederichs
Nathalia Friederichs

Posted on

Manipulating Dates with SQL Server

In the world of data management, dates play a crucial role. In software development projects, data analysis, and reporting, the ability to manipulate and understand temporal information is essential. SQL Server, one of the most widely used database management systems, provides a robust set of functions dedicated to date manipulation.

This article is a comprehensive guide on the various date manipulation functions available in SQL Server, ranging from simple ones like GETDATE() to more advanced ones like DATEADD(), DATEDIFF(), and others. Mastering these functions provides developers and data analysts with a powerful tool to handle complex date-related scenarios.

DATEADD()

The DATEADD function in SQL Server is used to add or subtract a specified time interval from a specific date. The syntax of the DATEADD function is as follows:

DATEADD(interval, number, date)

  • interval: is the part of the date to which the number will be added. This interval can be:
  1. Year: year, yy, yyyy
  2. Quarter: quarter, qq, q
  3. Month: month, mm, m
  4. Day of year: dayofyear, dy, y
  5. Day: day, dd, d
  6. Week: week, wk, ww
  7. Weekday: weekday, dw
  8. Hour: hour, hh
  9. Minute: minute, mi, n
  10. Second: second, ss, s
  11. Millisecond: millisecond, ms
  12. Microsecond: microsecond, mcs
  13. Nanosecond: nanosecond, ns
  • number: is the number of date parts to be added to the specified date. It can be positive (for addition) or negative (for subtraction).

  • date: is the date to which the interval is added.

Here are some practical examples of using DATEADD():

SELECT DATEADD(DAY, 3, '2023-01-01') AS NewDate

SELECT DATEADD(DAY, -3, '2023-01-01') AS NewDate

Note that DATEADD() does not modify the original date; it returns a new date value based on the addition or subtraction of the specified interval.

DATEDIFF()

In SQL Server, the DATEDIFF function is used to calculate the difference between two dates in terms of a specific interval, such as days, months, years, etc. The basic syntax of the function is as follows:

DATEDIFF(interval, start_date, end_date)

  • interval: is the interval you want to calculate, such as day for day, month for month, year for year, etc.

  • start_date: is the initial date used in the calculation.

  • end_date: is the final date used in the calculation.

Let's look at some practical examples:

SELECT DATEDIFF(DAY, '2023-01-01', '2023-01-10') AS DaysDifference

SELECT DATEDIFF(MONTH, '2023-05-01', '2023-10-01') AS MonthsDifference

SELECT DATEDIFF(YEAR, '2020-01-01', '2023-01-01') AS YearsDifference

It's important to note that the unit of measure for the difference can vary depending on the chosen interval. For example, if you calculate the difference in months, the result will be the number of complete months between the two dates. If you calculate in years, the result will be the number of complete years between the two dates.

Remember that DATEDIFF() does not modify the original date; it returns a new date value based on the addition or subtraction of the specified interval.

DATENAME()

The DATENAME() function in SQL Server is used to return a specific part of a date, such as the month name, day of the week, etc. This function always returns a string. The basic syntax of the function is as follows:

DATENAME(datepart, date)

  • datepart: is the part of the date you want to return, such as year, month, day, etc.

  • date: is the date from which you want to extract the specific part.

Here are some practical examples for better understanding:

SELECT DATENAME(MONTH, '2023-01-01') AS MonthName;

SELECT DATENAME(WEEKDAY, '2023-01-01') AS DayOfWeekName;

These commands will return "January" and "Sunday," respectively.

DATEPART()

The DATEPART() function in SQL Server is used to extract a specific part of a date, such as the year, month, day, hour, minute, etc. This function always returns an integer. The basic syntax of the function is as follows:

DATEPART(datepart, date)

  • datepart: is the part of the date you want to extract, such as year, month, day, etc.

  • date: is the date from which you want to extract the specific part.

Let's see a practical example of how the DATEPART() function works:

SELECT DATEPART(WEEKDAY, '2023-01-01') AS DayOfWeekNumber;

SELECT DATEPART(QUARTER, '2023-01-01') AS QuarterNumber;

In this case, the result will be 7 for the day of the week and 1 for the quarter.

DAY(), MONTH() & YEAR()

In SQL Server, the functions DAY(), MONTH(), and YEAR() are used to extract specific parts of a date. Each of these functions returns a numeric value corresponding to the specific part of the date.

A practical example of using the DAY() function:

SELECT DAY('2023-01-01')

The result will be 1.

Practical example using the MONTH() function:

SELECT MONTH('2023-02-01')

The result will be 2.

Example using the YEAR() function:

SELECT YEAR('2023-01-01')

The result will be 2023.

These functions are useful when you need to extract specific information from a date column or a specific date value. For example, when dealing with reports that need to group data by month or year, you can use these functions to extract this information from the date.

GETDATE()

The GETDATE() function in SQL Server is used to obtain the current date and time of the database server's system. This function does not require arguments and returns a value of the datetime type, representing the current date and time in the 'YYYY-MM-DD hh:mm:ss.sss' format.

The syntax of this function:

SELECT GETDATE() AS CurrentDate

GETUTCDATE()

The GETUTCDATE() function in SQL Server is similar to the GETDATE() function but returns the current date and time in the UTC (Coordinated Universal Time) format. UTC is a global time standard that does not vary due to factors such as daylight saving time or regional time zones. The use of UTC is common in distributed systems or when dealing with operations that require global consistency in time.

The syntax of this function:

SELECT GETUTCDATE() AS CurrentDateUTC

Unlike GETDATE(), which returns the local date and time of the SQL server, GETUTCDATE() provides the date and time relative to the UTC standard. This can be especially useful in distributed systems or environments where having a consistent and global time reference is crucial.

SYSDATETIME()

The SYSDATETIME() function in SQL Server is used to obtain the current date and time of the system, including fractional second information. It returns a value of the datetime2 type, which is an extension of the datetime type with higher precision, including fractions of a second.

The syntax for this function:

SELECT SYSDATETIME() AS CurrentDateTime

The main difference between SYSDATETIME() and GETDATE() is precision. SYSDATETIME() provides a more accurate representation of time, including fractions of a second, which can be useful in situations that require finer temporal resolution.

Remember that when choosing between SYSDATETIME() and GETDATE(), you should consider the need for temporal precision for your specific case. In many scenarios, the precision provided by SYSDATETIME() may be unnecessary, and GETDATE() may be sufficient.

ISDATE()

The ISDATE() function is used to check if an expression can be converted to a date and time data type. It returns 1 if the expression can be successfully converted to a date and 0 if it cannot. If the expression is null or cannot be converted to a date, the function will also return 0.
The basic syntax:

ISDATE(expression)

Now, let's go through practical examples:

SELECT ISDATE('2023-01-15') AS Result;

SELECT ISDATE('2023-02-30') AS Result;

The result will be 1 for the first example and 0 for the second example.

In summary, understanding these functions provides developers and data analysts with a solid foundation to effectively manipulate temporal information in SQL Server. The proper application of these functions contributes to robustness, accuracy, and efficiency in handling date-related data in SQL Server database environments. By incorporating these techniques into projects, professionals can significantly improve the quality and usefulness of their solutions, providing a richer and more informed experience for end users.

Top comments (0)