Display record with most recent time in MySQL


You can use ORDER BY STR_TO_DATE(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> DueTime varchar(20)
   -> );
Query OK, 0 rows affected (0.87 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('7:30AM');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('9:00PM');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('11:00PM');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output−

+---------+
| DueTime |
+---------+
| 7:30AM  |
| 9:00PM  |
| 11:00PM |
+---------+
3 rows in set (0.00 sec)

Here is the query to fetch records with most recent time −

mysql> select * from DemoTable
   -> order by str_to_date(DueTime, '%h:%i%p') desc limit 1;

This will produce the following output −

+---------+
| DueTime |
+---------+
| 11:00PM |
+---------+
1 row in set (0.00 sec)

Updated on: 26-Feb-2020

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements