Explain Codes LogoExplain Codes Logo

How do I subtract using SQL in MYSQL between two date time values and retrieve the result in minutes or seconds?

sql
timestampdiff
timediff
time_to_sec
Nikita BarsukovbyNikita Barsukov·Dec 16, 2024
TLDR

No time to lose. Use TIMESTAMPDIFF() to nimbly calculate the time difference between two datetime values. Don't like hours? Get your result in MINUTE or SECOND as per your need.

Minutes example:

-- Life is short, count the minutes! SELECT TIMESTAMPDIFF(MINUTE, start_time, end_time) AS minute_difference FROM table_of_life;

Seconds example:

-- Dude, have some patience, these are just seconds! SELECT TIMESTAMPDIFF(SECOND, start_time, end_time) AS second_difference FROM table_of_patience;

Precision, thy name is TIMEDIFF() and TIME_TO_SEC()

Give the clock maker a run for his money. Use TIMEDIFF() for time subtraction, and TIME_TO_SEC() to squeeze the difference into seconds.

-- A ticking clock has nothing on this! SELECT TIME_TO_SEC(TIMEDIFF(end_time, start_time)) AS second_difference from my_table_of_time;

Users, users, where are thou users?

Catch your users, based on timeframe. Flex the power of TIMESTAMPDIFF() with the WHERE clause.

-- Who was here in the last half-hour? Let's see! SELECT user_id, TIMESTAMPDIFF(MINUTE, last_login, NOW()) AS minutes_past FROM users WHERE TIMESTAMPDIFF(MINUTE, last_login, NOW()) < 30;

Edge cases: the SQL developer's final frontier

Dealing with time zone differences or daylight saving time shifts? Test, test, and test again. Arm your queries with robustness.

Enter TIMESTAMPDIFF(): A performance beast

Working with larger datasets? Need speed? Make TIMESTAMPDIFF() your partner in time.

-- Converting coffee into code since 1995 SELECT user_id, TIMESTAMPDIFF(SECOND, start_datetime, end_datetime) AS seconds_interval FROM user_sessions WHERE start_datetime BETWEEN '2023-01-01' AND '2023-01-31';

Indexes on start_datetime and end_datetime — the stuff of legends.

Military time: Friend or Foe?

Working with military time (24-hour clock)? Beware the negative values. Always confirm if your start time is later in the day than the end time on the previous day. No one wants their time travel adventure to end in a blackhole.