How to Calculate the Difference Between Two Timestamps in SQL

How to Calculate the Difference Between Two Timestamps in SQL

Do you ever find yourself needing to calculate the difference between two timestamps in SQL? If so, you're in luck! SQL has a handy way of calculating the difference between two timestamps that can help you get the answer you need.

The Solution

The solution is to use the TIMESTAMPDIFF function. This function takes three arguments: the unit of time you want to measure the difference in (e.g. seconds, minutes, hours, etc.), the start timestamp, and the end timestamp. For example, if you wanted to calculate the difference between two timestamps in seconds, you would use the following query:

SELECT TIMESTAMPDIFF(SECOND, start_timestamp, end_timestamp) FROM table_name;

Examples

Let's look at a few examples of how this function can be used. Suppose you have a table called events with the following data:


event_name      start_timestamp      end_timestamp
-----------------------------------------------
Meeting          2020-01-01 10:00    2020-01-01 11:00
Lunch            2020-01-01 12:00    2020-01-01 13:00

If you wanted to calculate the difference between the start and end timestamps of the Meeting event in seconds, you would use the following query:

SELECT TIMESTAMPDIFF(SECOND, start_timestamp, end_timestamp) FROM events WHERE event_name = 'Meeting';

This query would return the result 3600, since there are 3600 seconds in an hour.

Additional Info

The TIMESTAMPDIFF function is supported by most major databases, including MySQL, PostgreSQL, and SQL Server. However, the syntax may vary slightly depending on the database you are using. For more information, check out the documentation for your particular database. 🤓

Want to build your own LLM Apps with AirOps👇👇