MySQL DATE_ADD() to increment a date based on the value in another column?


Let us first create a table with one of the columns as DueDate and another one “RepeatTime, which displays how many times, let’s say a user was reminded to submit the payment −

mysql> create table DemoTable
   -> (
   -> DueDate date,
   -> RepeatTime int
   -> );
Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-01-23',3);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values('2019-06-22',6);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('2019-03-28',2);
Query OK, 1 row affected (0.25 sec)

mysql> insert into DemoTable values('2017-07-25',6);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+------------+------------+
| DueDate    | RepeatTime |
+------------+------------+
| 2019-01-23 |          3 |
| 2019-06-22 |          6 |
| 2019-03-28 |          2 |
| 2017-07-25 |          6 |
+------------+------------+
4 rows in set (0.00 sec)

Here is the query that increments date based in the values in another column −

mysql> update DemoTable set DueDate=date_add(DueDate,interval RepeatTime MONTH)
where RepeatTime!=6;
Query OK, 2 rows affected (0.25 sec)
Rows matched: 2 Changed: 2 Warnings: 0

Let us check table records once again −

mysql> select *from DemoTable;

Output

This will produce the following output −

+------------+------------+
| DueDate    | RepeatTime |
+------------+------------+
| 2019-04-23 | 3          |
| 2019-06-22 | 6          |
| 2019-05-28 | 2          |
| 2017-07-25 | 6          |
+------------+------------+
4 rows in set (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements