Comparing dates in MySQL ignoring time portion of a DateTime field?


To compare dates in MySQL except time portion of a datetime field, you can use DATE() function. The syntax is as follows −

select *from yourTableName where date(yourColumName) = yourDate;

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

mysql> create table ComparingDate
   −> (
   −> Name varchar(100),
   −> Login datetime
   −> );
Query OK, 0 rows affected (0.50 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into ComparingDate values('John','2014-04-06 22:50:45');
Query OK, 1 row affected (0.15 sec)

mysql> insert into ComparingDate values('Bob','2018-12-15 15:07:46');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ComparingDate values('Carol','2016-03-10 21:50:40');
Query OK, 1 row affected (0.18 sec)

mysql> insert into ComparingDate values('David','1995-08-08 23:40:47');
Query OK, 1 row affected (0.14 sec)

Display all records from table using select statement. The query is as follows −

mysql> select *from ComparingDate;

The following is the output −

+-------+---------------------+
| Name  | Login               |
+-------+---------------------+
| John  | 2014-04-06 22:50:45 |
| Bob   | 2018-12-15 15:07:46 |
| Carol | 2016-03-10 21:50:40 |
| David | 1995-08-08 23:40:47 |
+-------+---------------------+
4 rows in set (0.00 sec)

Here is the query to compare only date, not time −

mysql> select *from ComparingDate where date(Login) = '2016-03-10';

The following is the output −

+-------+---------------------+
| Name  | Login               |
+-------+---------------------+
| Carol | 2016-03-10 21:50:40 |
+-------+---------------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

634 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements