How do I find the difference between two dates with SQL?

Whether you’re:

  • calculating key supply chain indicators
  • trying to forecast orders/sales/revenue until the end of quarter/year,

you’re very likely to find yourself in the need of calculating the difference between two dates (timestamps)…

A way to go about it would be to use the datediff(‘years’, start date, current date) function.

The great thing about the datediff() function is that it is quite versatile when calculating the difference between dates.  Its syntax – datediff(‘time period’, start date, current date)  – allows it to calculate a time lapse ranging from a full year to just a second

That is, if you’re using Vertica or SQL Server.

As you’ll have noticed above, datediff() in MySQL is slightly different – it always gives the difference in number of days and it has the following syntax – datediff (timstamp 1, timestamp 2). 

So, should you want MySQL to calculate any other time period, you should be using timestampdiff(timstamp, start date, current date)

Conveniently, Vertica supports both datediff() and timestampdiff()!

PostgreSQL is yet a completely different story – if you’d like to have the difference between two days, you need to use age(current date,  start date)which will give you the full difference in years, months, days, hours, minutes and seconds

Happy SQL-ing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.