How to select a specific record from MySQL if date is in VARCHAR format?



For this, use STR_TO_DATE(). Let us first create a table −

mysql> create table DemoTable (    DueDate varchar(60) ) ; Query OK, 0 rows affected (0.71 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('12-AUG-2016'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('14-AUG-2018'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('24-AUG-2012'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('14-AUG-2012'); Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+ | DueDate    | +-------------+ | 12-AUG-2016 | | 14-AUG-2018 | | 24-AUG-2012 | | 14-AUG-2012 | +-------------+ 4 rows in set (0.00 sec)

Following is the query to select record from MySQL if date is in VARCHAR format. The STR_TO_DATE() method is used to convert string to date −

mysql> select *from DemoTable where str_to_date(DueDate,'%d-%M-%Y')=str_to_date('14-AUG-2012','%d-%M-%Y');

This will produce the following output −

+-------------+ | DueDate    | +-------------+ | 14-AUG-2012 | +-------------+ 1 row in set (0.00 sec)
Updated on: 2019-10-09T12:06:06+05:30

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements