mysql
  1. mysql-interval

MySQL Practicals: Interval

In MySQL, the INTERVAL function is used to add or subtract a time interval to a date or a datetime value. In this tutorial, we will cover the syntax, example, output, explanation, use, important points, and summary of using INTERVAL in MySQL.

Syntax

The syntax of the INTERVAL function is as follows:

date + INTERVAL expression unit

Here, date is a date or datetime value, expression is a numerical expression that represents the interval quantity, and unit is the unit of the interval, such as:

  • YEAR
  • MONTH
  • WEEK
  • DAY
  • HOUR
  • MINUTE
  • SECOND

Example

Let's say we want to add 5 days to a date value. Here's an example of how we can use INTERVAL to achieve this:

SELECT DATE('2022-01-01') + INTERVAL 5 DAY;

The output of this query will be:

2022-01-06

Explanation

In the example above, we used the INTERVAL function to add 5 days to the date value 2022-01-01. The expression 5 represents the interval quantity, and DAY is the interval unit. The DATE function is used to convert the string '2022-01-01' to a date value.

Use

The INTERVAL function can be used to perform calculations that involve date and time values, such as adding or subtracting a number of days, months, or years from a date, or adding or subtracting a number of hours, minutes, or seconds from a datetime value.

Important Points

  • The + operator can be used with the INTERVAL function to add a time interval to a date or datetime value.
  • The - operator can be used with the INTERVAL function to subtract a time interval from a date or datetime value.
  • The DATE function can be used to convert a string to a date value.

Summary

In this tutorial, we covered the syntax, example, output, explanation, use, and important points of using the INTERVAL function in MySQL. This function is useful for adding or subtracting time intervals from date or datetime values. By understanding how to use INTERVAL, you can perform more complex calculations involving dates and times in your MySQL queries.

Published on: