MySQL query to sort by both timestamp and enum?

MySQLMySQLi Database

For this, you can use ORDER BY DATE(). Let us first create a table. Here, we have a column with type DATE and another with type ENUM −

mysql> create table DemoTable
   -> (
   -> JoiningDate date,
   -> Status ENUM('Good','Excellent','Bad')
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-01-21','Excellent');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Status) values('Bad');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(Status) values('Good');
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 −

+-------------+-----------+
| JoiningDate | Status    |
+-------------+-----------+
| 2019-01-21  | Excellent |
| NULL        | Bad       |
| NULL        | Good      |
+-------------+-----------+
3 rows in set (0.00 sec)

Here is the query to sort order by both timestamp and enum −

mysql> select *from DemoTable
   -> order by DATE(JoiningDate) ASC, Status asc;

This will produce the following output −

+-------------+-----------+
| JoiningDate | Status    |
+-------------+-----------+
| NULL        | Good      |
| NULL        | Bad       |
| 2019-01-21  | Excellent |
+-------------+-----------+
3 rows in set (0.00 sec)
raja
Published on 17-Dec-2019 08:06:34
Advertisements