How to filter a specific month in MySQL when date is in varchar?

MySQLMySQLi Database

To filter, you can use STR_TO_DATE() function from MySQL. With that, use MONTH() to get the date from the specific month. Let us first create a table −

mysql> create table DemoTable
   -> (
  -> DueDate varchar(100)
   -> );
Query OK, 0 rows affected (1.18 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('06-19-2019');
Query OK, 1 row affected (0.36 sec)

mysql> insert into DemoTable values('01-31-2018');
Query OK, 1 row affected (0.38 sec)

mysql> insert into DemoTable values('12-01-2016');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+------------+
| DueDate    |
+------------+
| 06-19-2019 |
| 01-31-2018 |
| 12-01-2016 |
+------------+
3 rows in set (0.00 sec)

Here is the query to filter month in MySQL when date is in varchar −

mysql> select *from DemoTable
-> where month(str_to_date(DueDate, '%m-%d-%Y')) = 06;

Output

This will produce the following output −

+------------+
| DueDate    |
+------------+
| 06-19-2019 |
+------------+
1 row in set (0.00 sec)
raja
Published on 10-Jul-2019 10:09:06
Advertisements