How to order by date and time in MySQL?

MySQLMySQLi Database

You need to use ORDER BY clause for this. Let us first create a table. The query to create a table is as follows

mysql> create table OrderByDateThenTimeDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,  
   - > ShippingDate date,
   - > ShippingTime time
   - > );
Query OK, 0 rows affected (0.56 sec)

Now you can insert some records in the table using insert command. Here, we have two similar dates, but different times i.e. 2018-01-24

mysql> insert into OrderByDateThenTimeDemo(ShippingDate,ShippingTime) values('2018-01-24','16:45:40');
Query OK, 1 row affected (0.13 sec)
mysql> insert into OrderByDateThenTimeDemo(ShippingDate,ShippingTime) values('2018-01-24','15:30:35');
Query OK, 1 row affected (0.22 sec)
mysql> insert into OrderByDateThenTimeDemo(ShippingDate,ShippingTime) values('2018-04-25','14:20:25');
Query OK, 1 row affected (0.24 sec)
mysql> insert into OrderByDateThenTimeDemo(ShippingDate,ShippingTime) values('2019-02-14','18:07:55');
Query OK, 1 row affected (0.13 sec)
mysql> insert into OrderByDateThenTimeDemo(ShippingDate,ShippingTime) values('2019-01-31','20:20:30');
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from OrderByDateThenTimeDemo;

The following is the output

+----+--------------+--------------+
| Id | ShippingDate | ShippingTime |
+----+--------------+--------------+
|  1 | 2018-01-24   | 16:45:40     |
|  2 | 2018-01-24   | 15:30:35     |
|  3 | 2018-04-25   | 14:20:25     |
|  4 | 2019-02-14   | 18:07:55     |
|  5 | 2019-01-31   | 20:20:30     |
+----+--------------+--------------+
5 rows in set (0.00 sec)

Here is the query to order by date and time. The date would be ordered and then the time i.e. the time with similar dates would also be ordered.

mysql> select *from OrderByDateThenTimeDemo order by ShippingDate,ShippingTime;

The following is the output displaying the ordered date and time. For example, for date 2018-01-24, we have two values for time. Using the above query, we have successfully ordered the time as well i.e. 15:30:35 and 16:45:40

+----+--------------+--------------+
| Id | ShippingDate | ShippingTime |
+----+--------------+--------------+
|  2 | 2018-01-24   | 15:30:35     |
|  1 | 2018-01-24   | 16:45:40     |
|  3 | 2018-04-25   | 14:20:25     |
|  5 | 2019-01-31   | 20:20:30     |
|  4 | 2019-02-14   | 18:07:55     |
+----+--------------+--------------+
5 rows in set (0.00 sec)
raja
Published on 19-Mar-2019 14:51:40
Advertisements