Finding the Difference Between Two Dates in SQL
In this post, I’m going to talk about finding the difference between 2 dates in SQL. However, I’m going to cover it across multiple applications.
The Problem Statement is simple: How many days are there between two dates? What we want is an integer value back of how many days there are.
The solution will be slightly different depending on what application you’re using, so I’ll cover the ones I know about.
Teradata
Teradata uses the most obvious of solutions. Use the mathematical ‘minus’ approach to get the difference between two dates…
Quick, Easy, Obvious
SQL Server
SQL Server has a built in Function for getting the difference between two dates, called DATEDIFF()
The ‘d’ denotes that you want the answer back in ‘Days’, which is what we want.
But, the beauty of DATEDIFF() is that you can actually get your answer back in weeks, months, years, hours – whatever you want.
Eg,
Will give ’12’
For more details on how to use DATEDIFF, see This W3 Article
Access
Access achieves this in much the same way as SQL Server, with the same DATEDIFF() function. Only you must enclose your [Date Part] option in quotes.
You may have a few less options in Access than in SQL Server, but all the major ones are available.
VBA
Why note, eh?
VBA uses the same DATEDIFF() function as Access / SQLS
Excel
Wouldn’t be right not to include Excel!
A simple mathematical comparison will do the trick here – one date minus the other!
And there you have it – getting the difference in dates across different applications.
Update: To find the number of months/years between two dates in Excel, rather than just the number of days, you can also use the Excel DATEDIF function
Leave a Reply