How to find last date from records with date values in MySQL?


To get the last date i.e. the latest, use aggregate function MAX() with a subquery. Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ExpiryDate date
);
Query OK, 0 rows affected (1.40 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(ExpiryDate) values('2018-12-31');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(ExpiryDate) values('2019-09-01');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(ExpiryDate) values('2019-09-01');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(ExpiryDate) values('2016-08-30');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(ExpiryDate) values('2019-06-23');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+------------+
| Id | ExpiryDate |
+----+------------+
|  1 | 2018-12-31 |
|  2 | 2019-09-01 |
|  3 | 2019-09-01 |
|  4 | 2016-08-30 |
|  5 | 2019-06-23 |
+----+------------+
5 rows in set (0.00 sec)

Following is the query to find records with the last date −

mysql> select *from DemoTable
   where ExpiryDate=(select max(ExpiryDate) from DemoTable);

This will produce the following output. From the inserted records, the last date is 2019-09-0. The same can be seen in the below output −

+----+------------+
| Id | ExpiryDate |
+----+------------+
|  2 | 2019-09-01 |
|  3 | 2019-09-01 |
+----+------------+
2 rows in set (0.00 sec)

Updated on: 04-Oct-2019

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements