How to order by timestamp in MySQL?


To order by timestamp, use the ORDER BY as in the following syntax −

select *from yourTableName ORDER BY STR_TO_DATE(`yourColumnName`,'%m/%d/%Y%h:%i:%s %p');

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> `timestamp` varchar(100)
   -> );
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('06/22/2019 01:10:20 PM');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values('06/22/2019 12:00:27 PM');
Query OK, 1 row affected (0.26 sec)

mysql> insert into DemoTable values('06/22/2019 06:56:20 AM');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable values('06/22/2019 07:10:11 AM');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+------------------------+
| timestamp              |
+------------------------+
| 06/22/2019 01:10:20 PM |
| 06/22/2019 12:00:27 PM |
| 06/22/2019 06:56:20 AM |
| 06/22/2019 07:10:11 AM |
+------------------------+
4 rows in set (0.00 sec)

Following is the query to order by timestamp in MySQL −

mysql> select *from DemoTable ORDER BY STR_TO_DATE(`timestamp`,'%m/%d/%Y%h:%i:%s %p');

Output

This will produce the following output −

+------------------------+
| timestamp              |
+------------------------+
| 06/22/2019 06:56:20 AM |
| 06/22/2019 07:10:11 AM |
| 06/22/2019 12:00:27 PM |
| 06/22/2019 01:10:20 PM |
+------------------------+
4 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements