Compare only day and month with date field in MySQL?


You can compare only day and month with date field in MySQL with the help of DATE_FORMAT().

The syntax is as follows

select *from yourTableName
WHERE DATE_FORMAT(yourColumnName, '%m-%d') = DATE_FORMAT('yourValue', '%m-%d') and yourCondition;

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table compareDayAndMonthDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> compareDayAndTime date
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-01-31');
Query OK, 1 row affected (0.20 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2014-10-11');
Query OK, 1 row affected (0.16 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2016-09-12');
Query OK, 1 row affected (0.08 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2017-04-25');
Query OK, 1 row affected (0.08 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2018-12-25');
Query OK, 1 row affected (0.08 sec)
mysql> insert into compareDayAndMonthDemo(compareDayAndTime) values('2019-02-27');
Query OK, 1 row affected (0.07 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from compareDayAndMonthDemo;

The following is the output

+----+-------------------+
| Id | compareDayAndTime |
+----+-------------------+
| 1  | 2014-01-31        |
| 2  | 2014-10-11        |
| 3  | 2016-09-12        |
| 4  | 2017-04-25        |
| 5  | 2018-12-25        |
| 6  | 2019-02-27        |
+----+-------------------+
6 rows in set (0.00 sec)

Here is the query to compare only day and month

mysql> select *from compareDayAndMonthDemo
-> WHERE DATE_FORMAT(compareDayAndTime, '%m-%d') = DATE_FORMAT('2019-01-31', '%m-%d') and Id=1;

The following is the output

+----+-------------------+
| Id | compareDayAndTime |
+----+-------------------+
| 1  | 2014-01-31        |
+----+-------------------+
1 row in set (0.00 sec)

If you want only day and month, then use the below query

mysql> select DATE_FORMAT(compareDayAndTime, '%m-%d') AS DayAndMonthOnly from compareDayAndMonthDemo
-> WHERE DATE_FORMAT(compareDayAndTime, '%m-%d') = DATE_FORMAT('2019-01-31', '%m-%d') and Id=1;

The following is the output

+-----------------+
| DayAndMonthOnly |
+-----------------+
| 01-31           |
+-----------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements