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
-
‘YYYYMMDD’
The following example, the HumanResource.Employee table is queried to see the SQL date format of the HireDate values
123456USE AdventureWorks2014;GOSELECT HireDate,BusinessEntityID,LoginID, JobTitleFROM HumanResources.Employee;GONow, 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.
123SELECT HireDate,BusinessEntityID,LoginID, JobTitleFROM HumanResources.EmployeeWHERE HireDate = '20081207';
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
-
‘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.
1234SELECT HireDate,BusinessEntityID,LoginID, JobTitleFROM HumanResources.EmployeeWHERE HireDate = '12-07-2008';GO
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.
1 2 3 |
SELECT HireDate,BusinessEntityID,LoginID, JobTitle FROM HumanResources.Employee WHERE HireDate = '25-12-2008'; |
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’
1 2 3 4 5 6 |
SELECT HireDate, BusinessEntityID, LoginID, JobTitle FROM HumanResources.Employee WHERE CONVERT(DATE, HireDate, 103) = CONVERT(DATE, '25-12-2008', 103); |
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
1 2 3 |
SELECT DATEPART(YEAR, HireDate) AS [Year Part] FROM HumanResources.Employee; GO |
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
1 2 |
SELECT DATEPART(MONTH, HireDate) AS [Month Part] FROM HumanResources.Employee; |
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
1 2 3 |
SELECT DATEPART(QUARTER, HireDate) AS [Quarter Part] FROM HumanResources.Employee; GO |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
SELECT DATEPART(DAY, SOH.OrderDate) [Day Part], DATEPART(MONTH, SOH.OrderDate) [Month Part], DATEPART(QUARTER, SOH.OrderDate) [Quarter Part], DATEPART(YEAR, SOH.OrderDate) [Year Part], SUM(SOH.SubTotal) TotalSales FROM sales.SalesOrderHeader SOH JOIN sales.SalesOrderDetail SOD ON SOH.SalesOrderId = SOD.SalesOrderId GROUP BY DATEPART(DAY, SOH.OrderDate), DATEPART(QUARTER, SOH.OrderDate), DATEPART(YEAR, SOH.OrderDate), DATEPART(MONTH, SOH.OrderDate) ORDER BY DATEPART(QUARTER, SOH.OrderDate), DATEPART(YEAR, SOH.OrderDate), DATEPART(MONTH, SOH.OrderDate); |
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.
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.
1 2 3 |
SELECT DATENAME(WEEKDAY, HireDate) [Day], DATENAME(WEEK, HireDate) [Week], DATENAME(MONTH, HireDate) [Month], DATENAME(YEAR, HireDate) [YEAR] FROM HumanResources.Employee; GO |
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.
1 2 3 4 5 6 7 |
SELECT YEAR(SOH.OrderDate) as SalesYear, MONTH(SOH.OrderDate) as SalesMonth, SUM(SOH.SubTotal) AS TotalSales FROM sales.SalesOrderHeader SOH JOIN sales.SalesOrderDetail SOD ON SOH.SalesOrderId = SOD.SalesOrderId GROUP BY YEAR(SOH.OrderDate),MONTH(SOH.OrderDate) ORDER BY YEAR(SOH.OrderDate),MONTH(SOH.OrderDate) |
The output is an aggregated value of the TotalSales based on monthly sales.
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.
1 2 3 4 5 6 7 |
SELECT DATEDIFF(YEAR, HireDate, GETDATE()) No_Of_Years, DATEDIFF(MONTH, HireDate, GETDATE()) No_Of_Months, DATEDIFF(quarter, HireDate, GETDATE()) No_Of_Quarters, DATEDIFF(WEEK, HireDate, GETDATE()) Week_Of_Year, DATEDIFF(DAYOFYEAR, HireDate, GETDATE()) Day_Of_Year FROM HumanResources.Employee; GO |
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
1 2 3 4 5 |
SELECT DATEDIFF( hour, GETDATE(),GETDATE()+1 ) AS Hours, DATEDIFF( minute, GETDATE(), GETDATE()+1 ) AS Minutes, DATEDIFF( second,GETDATE(),GETDATE()+1 ) AS Seconds; GO |
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.
1 2 3 4 |
SELECT * FROM HumanResources.Employee WHERE DATEDIFF(MONTH, HireDate, GETDATE()) > 120; GO |
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.
1 2 |
SELECT DATEDIFF(YEAR, MIN(HireDate), MAX(HireDate)) No_Of_Years FROM HumanResources.Employee; |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
SELECT 'TodayDate', GETDATE() UNION ALL SELECT 'year', DATEADD(year, 1, GETDATE()) UNION ALL SELECT 'quarter', DATEADD(quarter, 1, GETDATE()) UNION ALL SELECT 'month', DATEADD(month, 1, GETDATE()) UNION ALL SELECT 'dayofyear', DATEADD(dayofyear, 1, GETDATE()) UNION ALL SELECT 'day', DATEADD(day, 1, GETDATE()) UNION ALL SELECT 'week', DATEADD(week, 1, GETDATE()) UNION ALL SELECT 'weekday', DATEADD(weekday, 1, GETDATE()) UNION ALL SELECT 'hour', DATEADD(hour, -1, GETDATE()) UNION ALL SELECT 'minute', DATEADD(minute, -30, GETDATE()) UNION ALL SELECT 'second', DATEADD(second, 1, GETDATE()) UNION ALL SELECT 'millisecond', DATEADD(millisecond, 1, GETDATE()) |
In the output, we can see that the value is operated on the GETDATE() function as per the defined datepart.
Note: DATEADD and DATEDIFF SQL function can be used in the SELECT, WHERE, HAVING, GROUP BY and ORDER BY clauses.
Datadiff vs Datediff_BIG
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
- Stairway to SQL essentials - April 7, 2021
- A quick overview of database audit in SQL - January 28, 2021
- How to set up Azure Data Sync between Azure SQL databases and on-premises SQL Server - January 20, 2021