EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL TIMESTAMPDIFF()
Secondary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Partitioning
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL AB
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

MySQL TIMESTAMPDIFF()

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.

Mathematically, It can also be written as below expression:

Timestampdiff = difference(datetime expression1-datetime expression2)

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

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,408 ratings)

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 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 mysql timestampdiff() function:

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

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

Unit type, datetime expression1 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 expression1and datetime expression2 are Date 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 largest is the YEAR.

MySQL TIMESTAMPDIFF Function with Examples

MySQL timestampdiff function with examples are 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 which will show 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:

 

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 onlythe 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 result of the query calculates only 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 have to 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 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 table,now it’s time to insert some records into it.

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 calculate the age of each children of child table:

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

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

In the above query, we have calculated the age of the child as on 2020-01-01. Also, if we want to calculate the present age of each child we can use 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 output of the query 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 type 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 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 select statement

select * from EmployeeEntry;

Output:

Output-1.7

Conclusion

In this article, we have learned about MySQL TIMESTAMPDIFF function, how to use it to solve our daily problem, its different use cases. We have also learned about its different units of timestampdiff function. We can use different units of this function according to our requirements. We have explained two real-world examples like age calculation and working hours of employee calculation.

Recommended Articles

This is a guide to MySQL TIMESTAMPDIFF(). Here we also discuss the introduction and syntax of mysql timestampdiff() function along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. IF Statement in MySQL
  2. MySQL Database Repair
  3. MySQL Timestamp
  4. Unique Key in MySQL
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

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

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

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

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

EDUCBA Login

Forgot Password?

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

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

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

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

EDUCBA

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

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

Let’s Get Started

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

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