
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements