Prashanth Jayaram

SQL date format Overview; DateDiff SQL function, DateAdd SQL function and more

October 31, 2018 by

SQL date format functions like the DateDiff SQL function and DateAdd SQL Function are oft used by DBAs but many of us never took the time to fully understand these extremely useful features. For professionals just getting started with SQL Server, these functions are some of the first to become familiar with. So hopefully this article will have a little something for everyone across the skill spectrum

One of the most interesting data types that are supported in the relational database world is DateTime. In this article, we’re going to take a look at working with date time data types in SQL Server. We’ll understand the basics of date-time data-type and also, we’ll see a various examples of how to query the date-time fields using built-in functions within SQL Server for manipulating the data, transforming date-time values and in few cases, perform arithmetic operations.

First, let’s go ahead take a look at some popular SQL date format and time functions.

By default, SQL Server inherently supports the languages that are supported by the Windows Operating System. Depending on locale and collation settings when you do the installation of SQL Server, the SQL date format display may be different. The kind of the data you’re going to play is determined based on locale setting and SQL Server collation setting.

In SQL Server, the data type DATE has two default Neutral Language Formats

  1. ‘YYYYMMDD’

    The following example, the HumanResource.Employee table is queried to see the SQL date format of the HireDate values

    Now, query the HireDate column using neutral language format. In the query, we’re passing integer value that consists of year, 2008; month, 12 and the 7th day.


    SQL DATE Format Examples

    Note: It basically means that the input value is numeric; the SQL engine internally converts it and actually ends up with a character value. So, it is surrounded by the single quotes

  2. ‘MM-DD-YYYY’ ( US-Based Format)

    In this SQL date format, the HireDate column is fed with the values ‘MM-DD-YYYY’. This is not an integer format. Let us run the same query with the new SQL date format of input value ‘12-07-2008’ to the HireDate column. So let’s run the following query and verify the output. The output is the same set of five records.


    sql date format in US format

    Note: The neutral language format values are implicit and SQL Server will do the necessary conversion. Any other SQL date format, requires a proper conversion of operands or/and values.

The following examples display an error message due to the improper use of the SQL date format.


https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-285.png

Now, the operand and its values are both converted to a standard format 103. You can refer here for more information about CAST and Convert functions. The following example returns all the rows of the employee where HireDate ’25-12-2008’


https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-286.png

Now let’s start taking a look at some of the date functions that SQL Server makes available for us and these date functions allow us to work with the different parts of the dates and even manipulate some of the functionality that we can work with in terms of dates.

Let’s look at the DATEPART SQL function. This function returns an integer value from the specified date column

Query the HireDate column to return only the year portion of the date

The following example generates an integer output column named [Year Part], and this should return only the year values

Query the HireDate column to return only the month portion of the date

The following example generates an integer output column named [Month Part], and this should return only the month values

Query the HireDate column to return only the Quarter portion of the date

The following example generates an integer output column named [Month Part], and this should return only the month values

The following example returns the sales details for the specific day of the orderDate field. The example also shows the usage of the DATEPART SQL function and its few associated arguments.

The SELECT statement selects the DATEPART, which is the function name, and it takes two arguments inside the parentheses. First, the datepart argument and the second, the date expression.

https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-287.png

Let’s take a look at using the DATENAME SQL function. This is similar to a DATEPART SQL function, but it returns a character string from the specified date field.


https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-288.png

Next, let’s take a look at the deterministic functions that returns date and time parts as an integer value. The following example returns integer values from the OrderDate field for the corresponding YEAR and MONTH functions.

The output is an aggregated value of the TotalSales based on monthly sales.

https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-289.png

Now let’s take a look at a couple of other different functions. And this one we’re going to look at is called DATEDIFF. The DATEDIFF SQL function returns a signed integer value that allows us to determine elapsed time between two dates.

Let us play with the query to use different date-parts to see the results.


https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-290.png

The following example returns the time parts between the two DateTime fields. In this example, hours, minutes, and seconds between the DateTime values are calculated using DATEDIFF SQL function


https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-291.png

How to use the DATEDIFF SQL function in the where clause

The following example returns all the employees who are working with the organization for more than 10 years. The conditional logic on the HireDate column is compared with greater than 120 months is mentioned in the where clause.


https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-292.png

How to use the DateDiff SQL function with an Aggregate function

The following example returns the number of years between the first hire date and the last hire date. In this case, we’re looking for the minimum HireDate and the maximum HireDate aggregate function used as input parameters for DATEDIFF SQL function. With these values, one could easily find the number of years existed between the first time hire and the last time hire.

Let’s take a look at the DATEADD SQL function. The functions add or subtract the value to the specified datepart and return the modified value of the datepart.

Let’s take a look at the following example. The value 1 is added to the various datepart and the value -1 is added to the hour datepart and -30 are added to minute datepart.

In the output, we can see that the value is operated on the GETDATE() function as per the defined datepart.

https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-293.png

Note: DATEADD and DATEDIFF SQL function can be used in the SELECT, WHERE, HAVING, GROUP BY and ORDER BY clauses.

Datadiff vs Datediff_BIG

DATEDIFF DATEDIFF_BIG
This is a very old function and it is available from the initial release SQL Server. With the birth of SQL Server 2016, Microsoft has introduced a new DATEDIFF SQL function, an enhanced version of DATEDIFF known as DATEDIFF_BIG.
Syntax
DATEDIFF(datepart, start_date, end_date)
Syntax
DATEDIFF_BIG(datepart,start_date,end_date)
The return type of the DATEDIFF SQL function is INTEGER(4 bytes) The return type of the DATEDIFF_BIG SQL function is BIGINT(8 bytes)
This function returns an integer value represents an elapsed time or day based on the defined DATEPART between the specified start DateTime and end DateTime This function returns a BIG integer value represents an elapsed time or day based on the defined DATEPART between the specified start DateTime and end DateTime
The integer value ranges between -2,147,483,648 to +2,147,483,647 The BIGINT datatype can store a value between the range -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)
Example: This example demonstrates the behavior of the DATEDIFF SQL function when the milliseconds difference between two dates is greater than the INT max (i.e. 2,147,483,647) value.

Error Message:
The DATEDIFF SQL function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.
Example: This example demonstrates the behavior of the DATEDIFF_BIG SQL function when the milliseconds difference between two dates is greater than the INT max (i.e. 2,147,483,647) value.

https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-294.png

https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-295.png
https://s33046.pcdn.co/wp-content/uploads/2018/10/word-image-296.png

That’s all for now on this SQL date format article …

Wrap Up

Thus far, we have seen very important SQL date format functions such as DATEPART, DATENAME, YEAR, MONTH, and DAY, with particular emphasis on the DATEADD SQL function and the DATEDIFF SQL function. SQL date formatfunctions in SQL server are really powerful and really helps to deliver impactful data analytics and reports. In some cases, it’s a matter of adjusting collation settings, location settings, simply readjusting the input stream of text value, or correction made the data source would suffice the date time problem.

It is recommended to use the neutral language format because it works better in most cases. At last, we see the difference between DATEDIFF SQL function and DATEDIFF_BIG SQL function. I hope you like this article. If you have any questions, feel free comment below


Prashanth Jayaram
168 Views