Sort by date & time in descending order in MySQL?


Let us create a table to sort date and time in ascending order. The query to create a table is as follows −

mysql> create table SortByDateAndTime
   -> (
   -> UserId int,
   -> UserName varchar(100),
   -> IssueDate date,
   -> IssueTime time
   -> );
Query OK, 0 rows affected (0.60 sec)

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

mysql> insert into SortByDateAndTime values(1,'John','2018-12-16','10:30');
Query OK, 1 row affected (0.14 sec)

mysql> insert into SortByDateAndTime values(2,'Bob','2018-12-16','10:10');
Query OK, 1 row affected (0.14 sec)

mysql> insert into SortByDateAndTime values(3,'Carol','2018-12-16','10:20');
Query OK, 1 row affected (0.10 sec)

mysql> insert into SortByDateAndTime values(4,'Sam','2018-12-16','10:00');
Query OK, 1 row affected (0.15 sec)

The query to display all records from the table using select statement is as follows −

mysql> select *from SortByDateAndTime;

Output

+--------+----------+------------+-----------+
| UserId | UserName | IssueDate  | IssueTime |
+--------+----------+------------+-----------+
|     1 | John      | 2018-12-16 | 10:30:00  |
|     2 | Bob       | 2018-12-16 | 10:10:00  |
|     3 | Carol     | 2018-12-16 | 10:20:00  |
|     4 | Sam       | 2018-12-16 | 10:00:00  |
+--------+----------+------------+-----------+
4 rows in set (0.00 sec)

Here is the query to sort date and time in descending order −

mysql> select UserId,UserName,date(IssueDate) as date1,IssueTime from
SortByDateAndTime
   -> order by date(IssueDate)desc,IssueTime desc;

The following is the output displaying in sorted date and time −

+--------+----------+------------+-----------+
| UserId | UserName | date1      | IssueTime |
+--------+----------+------------+-----------+
|      1 | John     | 2018-12-16 | 10:30:00  |
|      3 | Carol    | 2018-12-16 | 10:20:00  |
|      2 | Bob      | 2018-12-16 | 10:10:00  |
|      4 | Sam      | 2018-12-16 | 10:00:00  |
+--------+----------+------------+-----------+
4 rows in set (0.00 sec)

Or you can use another query to sort date and time. The query is as follows −

mysql> select UserId,UserName,date(IssueDate) as date1,IssueTime from
SortByDateAndTime
   -> order by date(IssueDate) desc,IssueTime asc;

Output

+--------+----------+------------+-----------+
| UserId | UserName | date1      | IssueTime |
+--------+----------+------------+-----------+
|      4 | Sam      | 2018-12-16 | 10:00:00  |
|      2 | Bob      | 2018-12-16 | 10:10:00  |
|      3 | Carol    | 2018-12-16 | 10:20:00  |
|      1 | John     | 2018-12-16 | 10:30:00  |
+--------+----------+------------+-----------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements