Persons (
CREATE TABLE
id INT AUTO_INCREMENT PRIMARY KEY,VARCHAR(255) NOT NULL,
full_name NULL
date_of_birth DATE NOT );
Timestampdiff
- Syntax:
TIMESTAMPDIFF(unit, begin, end)
- More on the definition is in Date & Time page
Calculate ages
- What if we want to calculate the ages of each person in the Persons table
create table
insert rows
Persons(full_name, date_of_birth)
INSERT INTO VALUES('John Doe', '1990-01-01'),
'David Taylor', '1989-06-06'),
('Peter Drucker', '1985-03-02'),
('Lily Smith', '1992-05-05'),
('Mary William', '1995-12-01'); (
calculate ages
- Let’s calculate the ages up to 2017/01/01
SELECT
id,
full_name,
date_of_birth,TIMESTAMPDIFF(YEAR,
date_of_birth,'2017-01-01') age
FROM persons;
- What if we want to calculate their ages up to NOW()
- Of course, just change the argument end
SELECT
id,
full_name,
date_of_birth,TIMESTAMPDIFF(YEAR,
date_of_birth,NOW()) age
FROM persons;
Calculate Intervals
Of course all TIMESTAMPDIFF does is calculate intervals, so let’s use it in a somehow (appears to be) complicated code chunk to
- calculate the time it took for a ride to be completed in
- minutes and milliseconds.
SELECTTIMESTAMPDIFF(
MINUTE,CAST('2021-01-01 14:01:05' AS TIMESTAMP),
CAST('2021-01-01 12:22:23' AS TIMESTAMP)) AS minutes_difference,
TIMESTAMPDIFF(
MILLISECOND,CAST('2021-01-01 01:44:33' AS TIMESTAMP),
CAST('2020-12-31 22:04:60' AS TIMESTAMP)) AS millisecond_difference;
:
Results: 98
minutes_difference: 13173000 millisecond_difference
Last N Seconds
- A common query is to look at values that occurred the last n seconds
- Here we can use both
TIMESTAMPDIFF
andTIMESTAMP
andTIMESTAMP_SUB
- date is the column from the table
- Note:
TIMESTAMPDIFF
is the difference between two times, units are specified - Note:
CURRENT_TIMESTAMP
is the datetime of now() - Note: we make use of
SUBQUERIES
to create anALIAS
date
SELECT
date,TIMESTAMPDIFF(SECOND,CURRENT_TIMESTAMP(), date) AS seconds_since
FROM
(TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 SECOND) AS date
SELECT
UNION ALLTIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 90 SECOND) AS date)
( SELECT
UNION ALLTIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 10 SECOND) AS date)
( SELECT
) AS table_3
WHERETIMESTAMPDIFF(SECOND, CURRENT_TIMESTAMP(), date) <= 30) (