MySQL query to update only month in date?

MySQLMySQLi Database

To update only month in date, use MONTH(). Let us first create a table −

mysql> create table DemoTable861(AdmissionDate date);
Query OK, 0 rows affected (1.22 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable861 values('2019-01-21');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable861 values('2018-01-01');
Query OK, 1 row affected (0.49 sec)
mysql> insert into DemoTable861 values('2016-01-02');
Query OK, 1 row affected (1.27 sec)
mysql> insert into DemoTable861 values('2018-01-14');
Query OK, 1 row affected (0.47 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable861;

This will produce the following output −

+---------------+
| AdmissionDate |
+---------------+
| 2019-01-21    |
| 2018-01-01    |
| 2016-01-02    |
| 2018-01-14    |
+---------------+
4 rows in set (0.00 sec)

Following is the query to update only month −

mysql> update DemoTable861
   set AdmissionDate=date_add(AdmissionDate,Interval -1 month)
   where month(AdmissionDate)=01;
Query OK, 4 rows affected (0.42 sec)
Rows matched : 4 Changed : 4 Warnings : 0

Let us check the table records once again −

mysql> select *from DemoTable861;

This will produce the following output −

+---------------+
| AdmissionDate |
+---------------+
| 2018-12-21    |
| 2017-12-01    |
| 2015-12-02    |
| 2017-12-14    |
+---------------+
4 rows in set (0.00 sec)
raja
Published on 03-Sep-2019 12:49:39
Advertisements