Compare date strings in MySQL

MySQLMySQLi Database

To compare date strings, use STR_TO_DATE() from MySQL.

Let us first create a table −

mysql> create table DemoTable712 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ArrivalDate varchar(100)
);
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable712(ArrivalDate) values('10.01.2019');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable712(ArrivalDate) values('11.12.2018');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable712(ArrivalDate) values('01.11.2017');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable712(ArrivalDate) values('20.06.2016');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable712;

This will produce the following output -

+----+-------------+
| Id | ArrivalDate |
+----+-------------+
| 1  | 10.01.2019  |
| 2  | 11.12.2018  |
| 3  | 01.11.2017  |
| 4  | 20.06.2016  |
+----+-------------+
4 rows in set (0.00 sec)

Following is the query to compare date strings −

mysql> select *from DemoTable712 where str_to_date(ArrivalDate,'%d.%m.%Y')='2017-11-01';

This will produce the following output -

+----+-------------+
| Id | ArrivalDate |
+----+-------------+
| 3  | 01.11.2017  |
+----+-------------+
1 row in set (0.00 sec)
raja
Published on 22-Aug-2019 07:07:00
Advertisements