How to select most recent date out of a set of several possible timestamps in MySQL?


You can select most recent date out of a set of several possible timestamps with the help of ORDER BY clause.

The syntax is as follows

SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY yourTimestampColumnName DESC LIMIT 1;

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

mysql> create table MostRecentDateDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Name varchar(10),
   - > ShippingDate timestamp
   - > );
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command. The query is as follows

mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Larry',date_add(now(),interval -1 month));
Query OK, 1 row affected (0.19 sec)
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Mike','2018-09-12 19:34:45');
Query OK, 1 row affected (0.43 sec)
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Sam','2017-11-24 14:30:40');
Query OK, 1 row affected (0.19 sec)
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Carol','2019-02-12 11:30:41');
Query OK, 1 row affected (0.56 sec)
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('David',now());
Query OK, 1 row affected (0.22 sec)
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('John','2018-12-31 12:59:58');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from MostRecentDateDemo;

The following is the output

+----+-------+---------------------+
| Id | Name  | ShippingDate        |
+----+-------+---------------------+
|  1 | Larry | 2019-01-14 17:17:08 |
|  2 | Mike  | 2018-09-12 19:34:45 |
|  3 | Sam   | 2017-11-24 14:30:40 |
|  4 | Carol | 2019-02-12 11:30:41 |
|  5 | David | 2019-02-14 17:19:34 |
|  6 | John  | 2018-12-31 12:59:58 |
+----+-------+---------------------+
6 rows in set (0.00 sec)

Here is the query to select most recent date

mysql> select Id,Name,ShippingDate from MostRecentDateDemo order by ShippingDate desc limit 1;

The following is the output

+----+-------+---------------------+
| Id | Name  | ShippingDate        |
+----+-------+---------------------+
|  5 | David | 2019-02-14 17:19:34 |
+----+-------+---------------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements