EDUCBA

EDUCBA

MENUMENU
  • Explore
    • Lifetime Membership
    • All in One Bundles
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign up
Home Data Science Data Science Tutorials MySQL Tutorial MySQL TIMESTAMPDIFF()

MySQL TIMESTAMPDIFF()

Updated June 1, 2023

MySQL TIMESTAMPDIFF()

Introduction to MySQL TIMESTAMPDIFF()

Mysql timestampdiff() is a one of the types of DATE function which is used to calculate the subtraction or the difference of two dates which might be of the same type or different.

ADVERTISEMENT
Popular Course in this category
MYSQL Course Bundle - 18 Courses in 1 | 3 Mock Tests

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Mathematically, It can also be written as below expression:

Timestampdiff = difference(datetime expression1-datetime expression2)

Where Both the datetime expression can be of different datatypes. One expression might be of datetime, and the second expression might be of date type, or both may consist of the same time, like date or datetime.

It is not always compulsory that both the datetime expression be of the same unit type. One might be a date, and another might be a datetime. The DATE type is mainly computed as a datetime with a default time written as’00:00:00′.

Syntax of MySQL TIMESTAMPDIFF() Function

Below is the syntax of the mysql timestampdiff() function:

TIMESTAMPDIFF (unit type, datetime expression1, datetime expression2);

Unit is used to express the difference of datetime or date in days, months, etc. Timestampdiff() function takes three arguments. They are:

Unit type, datetime expressions, and datetime expression2.It returns an integer as a result.

The TIMESTAMPDIFF function returns the output as first datetime expression1- second datetime expression2; here, datetime expression1 and datetime expression2 are Dates or Datetime expressions.

The unit argument defines the unit of the outcome of (datetime expression1-datetime expression2), which is represented as an integer

Below are the units of timestampdiff():

  • Microsecond
  • Second
  • Minute
  • Hour
  • Day
  • Week
  • Month
  • Quarter and
  • Year

The smallest unit that we can calculate timestampdiff function is SECOND, and the largest is YEAR.

MySQL TIMESTAMPDIFF Function with Examples

MySQL timestampdiff function with examples is given below:

1. Days

Below is the example that returns a difference of two date values, 2020-03-01 and 2020-03-10, in days:

Query:

select
timestampdiff(day,'2020-03-01', '2020-03-10')
AS result;

Output:

MySQL TIMESTAMPDIFF()-1.1

Here, AS means Alias, which means it will give a name result to the column, showing the calculated result of the query.

2. Months

Below is the example that returns a difference of two date values, 2020-03-01 and 2020-10-1, in months:

Query:

select
timestampdiff(month, '2020-03-01', '2020-10-1')
AS result;

Output:

MySQL TIMESTAMPDIFF()-1.2

3. Minutes

Below is the example that returns a difference of two DATETIME values in minutes:

Query:

select
timestampdiff(minute, '2020-01-03 10:10:00', '2020-01-03 10:30:00')
AS result;

Output:

MySQL TIMESTAMPDIFF()-1.3

Note: TIMESTAMPDIFF reflects only the time part.

Query:

select
timestampdiff(minute, '2020-05-18 10:00:00', '2020-05-18 7:45:41')
AS result;

Output:

MySQL TIMESTAMPDIFF()-1.3.1

Since we have passed the minute as the unit argument, the query’s result calculates only the minute and returns 45 as output. But the actual output should be 45 minutes and 41 seconds. If we want the output to be in second, we must pass second in the unit argument.

Query:

select
timestampdiff(second, '2020-05-18 10:00:00', '2020-05-18 7:45:41')
AS result;

Output:

Output-1.3.2

45 minutes 59 second = 45 x 60 + 41 (seconds) = 2741 seconds

4. Microseconds

Below is the example that returns a difference of two DATETIME values in microseconds:

Query:

select
timsetampdiff(microsecond, '2020-02-01 10:30:27.00000', '2020-02-01 10:30:27.123456')
AS result;

Output: 

Output-1.4

Use Cases of MySQL Timestamp Function with Examples

Use cases of the mysql timestamp function are given below:

How to Calculate the Age of A Child with Timestampdiff() Function?

Firstly, Let’s create a table with the name child for illustration:

create table child( Roll_no. INT auto_increment PRIMARY KEY,name varchar(100) NOT NULL, dob DATE NOT NULL);

After creating a table, it’s time to insert some records.

Insert into child(name,dob) values(('aman', '1990-01-01'),( 'rahul', '1989-06-06'),( 'ashish', '1985-03-02'),( 'divya', '1992-05-05'),( 'kunal', '1995-12-01'));

We can know to calculate the age of each child in the child table:

To fetch the records from the table, the child select statement is used after calculating each child’s timestamp difference of date of birth.

select
Roll_no,
name,
dob,
timestamp(year,dob, '2020-01-01') age
from
child;

In the above query, we have calculated the child’s age as of 2020-01-01. Also, if we want to calculate each child’s present age, we can use the now() function as a third argument of the timestampdiff function.

select
id,
name,
dob,
timestamp(year,dob,NOW()) age
from
child;

Negative Output of The Query:

If the first datetime argument is greater than the second date-time argument, the query output will be a negative number.

select
timestampdiff(day, '2020-04-22', '2020-04-4')
AS result;

Output:

Output-1.5

In the below example, we have taken the two different types of arguments

select
timestampdiff(minute, '2019-12-31', '2020-03-22 23:15:59')
AS result;

Output:

MySQL TIMESTAMPDIFF()-1.6

Calculate the Working Hours of Each Employee in the Second

For this, first, we will create a table named EmployeeEntry:

create table EmployeeEntry(
ClockInTime datetime,
ClockOutTime datetime,
Info INT(11) AS (ABS(TIMESTAMPDIFF(second,ClockInTime,ClockOutTime)))
)ENGINE=MyISAM;

We will now insert some records in the table EmployeeEntry:

insert into EmployeeEntry (ClockInTime, ClockOutTime) values('2020-07-22 9:30:00','2020-07-22 06:34:56');
insert into EmployeeEntry (ClockInTime, ClockOutTime) values('2020-12-11 10:00:00','2020-12-11 07:30:16');

To fetch all the records of the table, we will use a select statement

select * from EmployeeEntry;

Output:

Output-1.7

Conclusion

In this article, we have learned about MySQL’s TIMESTAMPDIFF function, how to use it to solve our daily problems, and its different use cases. We can utilize other units in the timestampdiff function depending on our requirements. Two real-life scenarios where this function can be helpful to are when we need to calculate a person’s age or figure out an employee’s working hours.

Recommended Articles

We hope that this EDUCBA information on “MySQL TIMESTAMPDIFF()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. IF Statement in MySQL
  2. MySQL Database Repair
  3. MySQL Timestamp
  4. Unique Key in MySQL
ADVERTISEMENT
C++ PROGRAMMING Course Bundle - 9 Courses in 1 | 5 Mock Tests
40+ Hour of HD Videos
9 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
ASP.NET Course Bundle - 28 Courses in 1 | 5 Mock Tests
123+ Hours of HD Videos
28 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
SQL Course Bundle - 51 Courses in 1 | 6 Mock Tests
205+ Hours of HD Videos
51 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
SOFTWARE TESTING Course Bundle - 13 Courses in 1
53+ Hour of HD Videos
13 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Footer
Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
  • Blog as Guest
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Cyber Monday Reloaded Price Drop! All in One Universal Bundle (3700+ Courses) @ 🎁 90% OFF - Ends in ENROLL NOW