Insert datetime into another datetime field in MySQL?


You can achieve this with the help of update command. To understand the method, let us create a table. The query to create a table is as follows −

mysql> create table AddDateTimeWithOther
   −> (
   −> Id int,
   −> IssueDate datetime,
   −> DueDate datetime
   −> );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table with insert statement. The query is as follows −

mysql> insert into AddDateTimeWithOther values(100,now(),date_add(now(),interval -3 year));
Query OK, 1 row affected (0.13 sec)

mysql> insert into AddDateTimeWithOther values(101,now(),date_add(now(),interval 2 year));
Query OK, 1 row affected (0.20 sec)

Display all records from the table with the help of select statement. The query is as follows −

mysql> select *from AddDateTimeWithOther;

The following is the output −

+------+---------------------+---------------------+
| Id   | IssueDate           | DueDate             |
+------+---------------------+---------------------+
| 100 | 2018-12-11 17:33:28 | 2015-12-11 17:33:28  |
| 101 | 2018-12-11 17:33:37 | 2020-12-11 17:33:37  |
+------+---------------------+---------------------+
2 rows in set (0.00 sec)

Now if you want to set some other date in place of “DueDate” ‘2015-12-11 17:33:28, then use the UPDATE command. The below query displays the same by updating the Due Date to ‘2019-12-11 17:35:03’.

The query is as follows −

mysql> update AddDateTimeWithOther set DueDate = date_add(now(),interval 1 year) where Id = 100;
Query OK, 1 row affected (0.24 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Now you can check the data has been inserted or not. The query is as follows −

mysql> select *from AddDateTimeWithOther;

The following is the output displaying the update worked successfully and the date inserted −

+------+---------------------+---------------------+
| Id   | IssueDate           | DueDate             |
+------+---------------------+---------------------+
| 100  | 2018-12-11 17:33:28 | 2019-12-11 17:35:03 |
| 101  | 2018-12-11 17:33:37 | 2020-12-11 17:33:37 |
+------+---------------------+---------------------+
2 rows in set (0.00 sec)

Updated on: 30-Jul-2019

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements