Example analysis of interval calculation of mysql date and time

Example analysis of interval calculation of mysql date and time

This article uses an example to describe the interval calculation of MySQL date and time. Share with you for your reference, the details are as follows:

First of all, we have to make it clear that MySQL interval values ​​are mainly used for date and time calculations. If we want to create interval values, we can use the following expression:

INTERVAL expr unit

Then, we need to understand that the INTERVAL keyword is the expr that determines the interval value, and the unit that specifies the interval unit. For example, to create a 1-day interval, we would use the following expression:

INTERVAL 1 DAY

Note, however, that INTERVAL and UNIT are not case-sensitive, so the following expression is equivalent to the above expression:

interval 1 day

The actual usage and syntax of interval values ​​for date and time arithmetic can be seen in the following code:

date + INTERVAL expr unit
date - INTERVAL expr unit

Interval values ​​are also used by various time functions such as DATE_ADD, DATE_SUB, TIMESTAMPADD, and TIMESTAMPDIFF. MySQL defines the standard format of expr and unit, as shown in the following table:

Unit expression (expr)
DAY DAYS
DAY_HOUR 'DAYS HOURS'
DAY_MICROSECOND 'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS'
DAY_MINUTE 'DAYS HOURS:MINUTES'
DAY_SECOND 'DAYS HOURS:MINUTES:SECONDS'
HOUR HOURS
HOUR_MICROSECOND 'HOURS:MINUTES:SECONDS.MICROSECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
MICROSECOND MICROSECONDS
MINUTE MINUTES
MINUTE_MICROSECOND 'MINUTES:SECONDS.MICROSECONDS'
MINUTE_SECOND 'MINUTES:SECONDS'
MONTH MONTHS
QUARTER QUARTERS
SECOND SECONDS
SECOND_MICROSECOND 'SECONDS.MICROSECONDS'
WEEK WEEKS
YEAR YEARS
YEAR_MONTH 'YEARS-MONTHS'

Let's take a look at an example. The following SQL statement adds 1 day to the date 2020-01-01 and returns the result as 2020-01-02:

mysql> SELECT '2020-01-01' + INTERVAL 1 DAY;
+-------------------------------+
| '2020-01-01' + INTERVAL 1 DAY |
+-------------------------------+
| 2020-01-02 |
+-------------------------------+
1 row in set (0.01 sec)

If we use an interval value in an expression involving DATE or DATETIME values ​​and the interval value is on the right side of the expression, we can use a negative value of expr as shown in the following example:

mysql> SELECT '2020-01-01' + INTERVAL -1 DAY;
+--------------------------------+
| '2020-01-01' + INTERVAL -1 DAY |
+--------------------------------+
| 2019-12-31 |
+--------------------------------+
1 row in set

Let's look at how to use DATE_ADD and DATE_SUB to add/subtract 1 month from a date value:

mysql> SELECT DATE_ADD('2020-01-01', INTERVAL 1 MONTH) 1_MONTH_LATER, 
    DATE_SUB('2020-01-01',INTERVAL 1 MONTH) 1_MONTH_BEFORE;
+---------------+----------------+
| 1_MONTH_LATER | 1_MONTH_BEFORE |
+---------------+----------------+
| 2020-02-01 | 2019-12-01 |
+---------------+----------------+
1 row in set

Let's look at a SQL statement that uses the TIMESTAMPADD(unit, interval, expression) function to add 30 minutes to a timestamp value:

mysql> SELECT TIMESTAMPADD(MINUTE,30,'2020-01-01') 30_MINUTES_LATER;
+---------------------+
| 30_MINUTES_LATER |
+---------------------+
| 2020-01-01 00:30:00 |
+---------------------+
1 row in set

After saying so much, you may still be a little confused. Don't worry, let's take a look at the specific operations. We create a new table called memberships for demonstration:

CREATE TABLE memberships (
  id INT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(355) NOT NULL,
  plan VARCHAR(255) NOT NULL,
  expired_date DATE NOT NULL
);

In the memberships table above, the expired_date column stores the membership expiration date of each member. Now let's insert some data into the memberships table:

INSERT INTO memberships(email, plan, expired_date)
VALUES('[email protected]','Gold','2018-07-13'),
   ('[email protected]','Platinum','2018-07-10'),
   ('[email protected]','Silver','2018-07-15'),
   ('[email protected]','Gold','2018-07-20'),
   ('[email protected]','Silver','2018-07-08');

Now let's assume that today is 2018-07-06, and then we use SQL statements to query members whose membership will expire in the next 7 days:

SELECT 
  email,
  plan,
  expired_date,
  DATEDIFF(expired_date, '2018-07-06') remaining_days
FROM
  memberships
WHERE
  '2018-07-06' BETWEEN DATE_SUB(expired_date, INTERVAL 7 DAY) AND expired_date;

After executing the above query statement, the following results are obtained:

+--------------------------+----------+--------------+----------------+
| email | plan | expired_date | remaining_days |
+--------------------------+----------+--------------+----------------+
| [email protected] | Gold | 2018-07-13 | 7 |
| [email protected] | Platinum | 2018-07-10 | 4 |
| [email protected] | Silver | 2018-07-08 | 2 |
+--------------------------+----------+--------------+----------------+
3 rows in set

In the above SQL, the DATE_SUB function subtracts 7 days from the expiration date specified by the interval value (INTERVAL 7 DAY). That is to say, if the original date of a certain data is the 13th, minus seven days, it will be the 6th. This is roughly what it means. I believe everyone has a certain understanding of it.

That’s all for today.

Readers who are interested in more MySQL-related content can check out the following topics on this site: "MySQL query skills", "MySQL transaction operation skills", "MySQL stored procedure skills", "MySQL database lock related skills summary" and "MySQL common function summary"

I hope this article will be helpful to everyone's MySQL database design.

You may also be interested in:
  • How to use MySQL DATEDIFF function to get the time interval between two dates
  • MySQL implements increasing or decreasing the specified time interval for all times in the current data table (recommended)
  • MySQL DATE_ADD and ADDDATE functions add a specified time interval to a date

<<:  Guide to using env in vue cli

>>:  OpenSSL implements two-way authentication tutorial (with server and client code)

Recommend

17 excellent web designs carefully crafted by startups

Startups often bring us surprises with their unco...

Implementation code for installing vsftpd in Ubuntu 18.04

Install vsftpd $ sudo apt-get install vsftpd -y S...

Three ways to configure Nginx virtual hosts (based on domain names)

Nginx supports three ways to configure virtual ho...

MySQL master-slave replication principle and points to note

Written in front I have been writing a special to...

Keepalived implements Nginx load balancing and high availability sample code

Chapter 1: Introduction to keepalived The purpose...

MySQL multi-instance installation boot auto-start service configuration process

1.MySQL multiple instances MySQL multi-instance m...

Solution to the problem that order by is not effective in MySQL subquery

By chance, I discovered that a SQL statement prod...

Example of how to set up a Linux system to automatically run a script at startup

Preface Hello everyone, I am Liang Xu. At work, w...

The Complete List of MIME Types

What is MIME TYPE? 1. First, we need to understan...

XHTML tags that are easily confused by the location of the use

<br />We have always emphasized semantics in...

Mysql case analysis of transaction isolation level

Table of contents 1. Theory SERIALIZABLE REPEATAB...

How to design and create adaptive web pages

With the popularization of 3G, more and more peop...

Summary of react basics

Table of contents Preface start React Lifecycle R...

Details on how to use class styles in Vue

Table of contents 1. Boolean 2. Expression 3. Mul...

Some ways to eliminate duplicate rows in MySQL

SQL statement /* Some methods of eliminating dupl...