Preserve select order within MySQL UNION?

MySQLMySQLi Database

It’s a good choice to use CASE statement. Do not use UNION. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ShippingDate datetime
   );
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(ShippingDate) values('2019-04-21');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(ShippingDate) values('2019-01-01');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(ShippingDate) values('2019-05-11');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(ShippingDate) values('2018-12-31');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(ShippingDate) values('2019-02-18');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+---------------------+
| Id | ShippingDate        |
+----+---------------------+
| 1  | 2019-04-21 00:00:00 |
| 2  | 2019-01-01 00:00:00 |
| 3  | 2019-05-11 00:00:00 |
| 4  | 2018-12-31 00:00:00 |
| 5  | 2019-02-18 00:00:00 |
+----+---------------------+
5 rows in set (0.00 sec)

Following is the query to preserve select order using order by case.

mysql> select *from DemoTable
   ORDER
   BY CASE WHEN ShippingDate < CURDATE() THEN ShippingDate ELSE CURDATE() END DESC,
ShippingDate ASC;

This will produce the following output −

+----+---------------------+
| Id | ShippingDate        |
+----+---------------------+
| 3  | 2019-05-11 00:00:00 |
| 1  | 2019-04-21 00:00:00 |
| 5  | 2019-02-18 00:00:00 |
| 2  | 2019-01-01 00:00:00 |
| 4  | 2018-12-31 00:00:00 |
+----+---------------------+
5 rows in set (0.00 sec)
raja
Published on 21-May-2019 07:58:33
Advertisements