The easiest way to insert date records in MySQL?


Use the STR_TO_DATE() method to insert date records as in the below syntax −

select str_to_date(yourColumnName,'%b %Y') from yourTableName;

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> JoiningYear varchar(20)
   -> );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Jan 2018');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('May 2107');
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable values('Aug 2019');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Oct 2020');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+
| JoiningYear |
+-------------+
| Jan 2018    |
| May 2107    |
| Aug 2019    |
| Oct 2020    |
+-------------+
4 rows in set (0.00 sec)

Here is the query to insert date records in MySQL −

mysql> select str_to_date(JoiningYear,'%b %Y') from DemoTable;

This will produce the following output −

+----------------------------------+
| str_to_date(JoiningYear,'%b %Y') |
+----------------------------------+
| 2018-01-00                       |
| 2107-05-00                       |
| 2019-08-00                       |
| 2020-10-00                       |
+----------------------------------+
4 rows in set (0.05 sec)

Updated on: 17-Dec-2019

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements