How to insert date record to the same table with different date formats with MySQL?


For this, you can use the INSERT INTO SELECT statement. To format the date, use the DATE_FORMAT() function. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> DateOfJoining datetime,
   -> JoiningDate text
   -> );
Query OK, 0 rows affected (0.79 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(DateOfJoining) values('2019-10-26 13:52:10');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(DateOfJoining) values('2018-12-31 15:20:40');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement−

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+-------------+
| DateOfJoining       | JoiningDate |
+---------------------+-------------+
| 2019-10-26 13:52:10 | NULL        |
| 2018-12-31 15:20:40 | NULL        |
+---------------------+-------------+
2 rows in set (0.00 sec)

Here is the query to insert date record to the same table with different date formats −

mysql> insert into DemoTable(JoiningDate) select date_format(DateOfJoining , '%W %e, %b %Y @ %r') from DemoTable;
Query OK, 2 rows affected (0.13 sec)
Records: 2 Duplicates: 0 Warnings: 0

Let us check the table records once again−

mysql> select *from DemoTable;

This will produce the following output−

+---------------------+-------------------------------------+
| DateOfJoining       | JoiningDate                         |
+---------------------+-------------------------------------+
| 2019-10-26 13:52:10 | NULL                                |
| 2018-12-31 15:20:40 | NULL                                |
| NULL                | Saturday 26, Oct 2019 @ 01:52:10 PM |
| NULL                | Monday 31, Dec 2018 @ 03:20:40 PM |
+---------------------+-------------------------------------+
4 rows in set (0.00 sec)

Updated on: 12-Dec-2019

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements