MySQL query to find latest 3 dates in a table and the resultant dates shouldn’t be duplicate

MySQLi DatabaseMySQL

To find the latest dates, order the date records with ORDER BY DESC. Since we want only 3 dates, use LIMIT 3.

Let us first create a table −

mysql> create table DemoTable
(
   AdmissionDate date
);
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-09-04');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('2019-08-10');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('2019-09-21');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('2019-09-18');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('2019-09-21');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('2019-08-18');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2019-09-18');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('2019-09-16');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------+
| AdmissionDate |
+---------------+
| 2019-09-04    |
| 2019-08-10    |
| 2019-09-21    |
| 2019-09-18    |
| 2019-09-21    |
| 2019-08-18    |
| 2019-09-18    |
| 2019-09-16    |
+---------------+
8 rows in set (0.00 sec)

Following is the query to find the latest 3 dates in a table −

mysql> select AdmissionDate from (select distinct AdmissionDate from DemoTable) tbl order by AdmissionDate desc limit 3;

This will produce the following output −

+---------------+
| AdmissionDate |
+---------------+
| 2019-09-21    |
| 2019-09-18    |
| 2019-09-16    |
+---------------+
3 rows in set (0.00 sec)
raja
Published on 04-Oct-2019 08:27:44
Advertisements