Order Timestamp Values in Ascending Order in MySQL



You can use ORDER BY ASC to order timestamp values in ascending order.

The following is the syntax without using TIMESTAMP() −

SELECT yourTimestampColumnName from yourTableName
order by yourTimestampColumnName ASC;

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

mysql> create table Timestamp_TableDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> yourTimestamp timestamp
   -> );
Query OK, 0 rows affected (0.83 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into Timestamp_TableDemo(yourTimestamp) values('2019-02-06 17:34:57');
Query OK, 1 row affected (0.14 sec)
mysql> insert into Timestamp_TableDemo(yourTimestamp) values('2019-02-06 17:32:30');
Query OK, 1 row affected (0.25 sec)
mysql> insert into Timestamp_TableDemo(yourTimestamp) values('2019-02-06 17:32:09');
Query OK, 1 row affected (0.14 sec)

Now you can display all records from the table using a select statement. The query is as follows −

mysql> select *from Timestamp_TableDemo;

The following is the output −

+----+---------------------+
| Id | yourTimestamp       |
+----+---------------------+
|  1 | 2019-02-06 17:34:57 |
|  2 | 2019-02-06 17:32:30 |
|  3 | 2019-02-06 17:32:09 |
+----+---------------------+
3 rows in set (0.00 sec)

Here is the query to order timestamp values in ascending order −

mysql> select yourTimestamp from Timestamp_TableDemo
   -> order by yourTimestamp ASC;

The following is the output −

+---------------------+
| yourTimestamp       |
+---------------------+
| 2019-02-06 17:32:09 |
| 2019-02-06 17:32:30 |
| 2019-02-06 17:34:57 |
+---------------------+
3 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:24+05:30

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements