MySQL query to order by current day and month?

MySQLMySQLi Database

For this, you can use the ORDER BY CASE statement. Let us first create a table −

mysql> create table DemoTable
(
   DueDate date
);
Query OK, 0 rows affected (0.56 sec)

Note − Let’s say the current date is 2019-07-22.

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-03-10');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('2019-08-25');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2019-06-01');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('2019-12-31');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------+
| DueDate    |
+------------+
| 2019-03-10 |
| 2019-08-25 |
| 2019-06-01 |
| 2019-12-31 |
+------------+
4 rows in set (0.00 sec)

Following is the query to order by day and month −

mysql> select *from DemoTable order by case when DueDate > curdate() then 0 else 1 end, DueDate;

This will produce the following output −

+------------+
| DueDate    |
+------------+
| 2019-08-25 |
| 2019-12-31 |
| 2019-03-10 |
| 2019-06-01 |
+------------+
4 rows in set (0.00 sec)
raja
Published on 26-Sep-2019 11:39:57
Advertisements