MySQL TIMESTAMPADD() Function

Summary: in this tutorial, you will learn how to use the MySQL TIMESTAMPADD() function to add or subtract intervals from a timestamp or date.

Introduction to MySQL TIMESTAMPADD() function

The TIMESTAMPADD() function allows you to add or subtract intervals from a timestamp or date.

Here’s the syntax of the TIMESTAMPADD() function:

TIMESTAMPADD(unit, interval, timestamp)Code language: SQL (Structured Query Language) (sql)

In this syntax:

  • unit: This is the unit of time that you want to add (e.g., SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR).
  • interval: This is the number of intervals you want to add (can be a positive or negative integer).
  • timestamp: This is the timestamp or date to which you want to add the interval.

The TIMESTAMPADD() function returns a new date or timestamp with the new.

It returns NULL if interval or timestamp is NULL.

MySQL TIMESTAMPADD() function examples

Let’s take some examples of using the MySQL TIMESTAMPADD() function.

1) Basic usage of TIMESTAMPADD() function example

The following example uses the TIMESTAMPADD() function to add days to a given timestamp:

SELECT 
  TIMESTAMPADD(DAY, 7, '2023-10-19 15:30:00') AS new_timestampCode language: SQL (Structured Query Language) (sql)

Output:

+---------------------+
| new_timestamp       |
+---------------------+
| 2023-10-26 15:30:00 |
+---------------------+
1 row in set (0.01 sec)Code language: SQL (Structured Query Language) (sql)

In this example, we use the TIMESTAMPADD() function to add seven days to the timestamp '2023-10-19 15:30:00'.

2) Using TIMESTAMPADD() with different intervals

The following example uses the TIMESTAMPADD() function to add three months to the date '2022-07-15':

SELECT 
  TIMESTAMPADD(MONTH, 3, '2022-07-15') AS new_date;Code language: SQL (Structured Query Language) (sql)

Output:

+------------+
| new_date   |
+------------+
| 2022-10-15 |
+------------+
1 row in set (0.00 sec)Code language: SQL (Structured Query Language) (sql)

Summary

  • Use the TIMESTAMPADD() function to add or subtract intervals from a timestamp or date.
Was this tutorial helpful?