MySQL to perform DateTime comparison and find the difference between dates in different columns


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

mysql> create table DemoTable(DOB datetime,CurrentDate datetime);
Query OK, 0 rows affected (0.59 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('1995-01-21',CURDATE());
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('1998-11-01',CURDATE());
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable values('2000-10-24',CURDATE());
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+---------------------+
| DOB                 | CurrentDate         |
+---------------------+---------------------+
| 1995-01-21 00:00:00 | 2019-07-08 00:00:00 |
| 1998-11-01 00:00:00 | 2019-07-08 00:00:00 |
| 2000-10-24 00:00:00 | 2019-07-08 00:00:00 |
+---------------------+---------------------+
3 rows in set (0.00 sec)

Following is the query for datetime comparison −

mysql> select *from DemoTable where (datediff(CurrentDate,DOB) / 365) > 23;

This will produce the following output −

+---------------------+---------------------+
| DOB                 | CurrentDate         |
+---------------------+---------------------+
| 1995-01-21 00:00:00 | 2019-07-08 00:00:00 |
+---------------------+---------------------+
1 row in set (0.00 sec)

Updated on: 22-Aug-2019

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements