Change only dates, ignoring time records in MySQL


To change only dates, not time, use the MySQL INTERVAL and YEAR. Since, we will be updating the records, therefore, use UPDATE and set a new value with INTERVAL.

Let us see an example and create a table −

mysql> create table DemoTable
(
   DueDate datetime
);
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2017-08-12 10 :30 :45');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('2015-09-21 12 :00 :00');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('2018-12-31 11 :45 :56');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2016-01-02 01 :23 :04');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+
| DueDate             |
+---------------------+
| 2017-08-12 10 :30 :45 |
| 2015-09-21 12 :00 :00 |
| 2018-12-31 11 :45 :56 |
| 2016-01-02 01 :23 :04 |
+---------------------+
4 rows in set (0.00 sec)

Following is the query to change all dates but not the time values −

mysql> update DemoTable
   set DueDate=DueDate+interval 1 year;
Query OK, 4 rows affected (0.16 sec)
Rows matched : 4 Changed : 4 Warnings : 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+
| DueDate             |
+---------------------+
| 2018-08-12 10 :30 :45 |
| 2016-09-21 12 :00 :00 |
| 2019-12-31 11 :45 :56 |
| 2017-01-02 01 :23 :04 |
+---------------------+
4 rows in set (0.00 sec)
raja
Published on 07-Oct-2019 16:22:42
Advertisements