How to Calculate the Difference Between Two DateTimes in SQL

To calculate the difference between two datetimes in SQL, use the DATEDIFF() function. This function takes three arguments: the unit of time you want to calculate the difference in (e.g. days, hours, minutes, etc.), the start datetime, and the end datetime. For example, if you wanted to calculate the difference between two datetimes in days, you would use the following query:

SELECT DATEDIFF(day, start_datetime, end_datetime) 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:

events
event_namestart_datetimeend_datetime
Party2020-01-01 12:002020-01-02 12:00
Concert2020-02-01 12:002020-02-02 12:00


If you wanted to calculate the difference between the start and end datetimes of the Party event in days, you would use the following query:

SELECT DATEDIFF(day, start_datetime, end_datetime) FROM events WHERE event_name = 'Party';

This query would return the result 1, since the Party event lasted one day.

Additional Info

The DATEDIFF() 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👇👇