Let us first create a table −
mysql> create table DemoTable1526 -> ( -> CustomerName varchar(20), -> PurchaseDate date -> ); Query OK, 0 rows affected (0.67 sec)
Insert some records in the table using insert command. Here, we have inserted 2019 dates −
mysql> insert into DemoTable1526 values('Adam','2019-06-01'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1526 values('Sam','2019-04-26'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1526 values('Chris','2019-05-24'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1526 values('David','2019-10-10'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable1526 values('Bob','2019-12-31'); Query OK, 1 row affected (0.23 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1526;
This will produce the following output −
+--------------+--------------+ | CustomerName | PurchaseDate | +--------------+--------------+ | Adam | 2019-06-01 | | Sam | 2019-04-26 | | Chris | 2019-05-24 | | David | 2019-10-10 | | Bob | 2019-12-31 | +--------------+--------------+ 5 rows in set (0.00 sec)
The current date is as follows −
mysql> select curdate(); +------------+ | curdate() | +------------+ | 2019-10-08 | +------------+ 1 row in set (0.00 sec)
Here is the query to order by last 3 months first of 2019, then alphabetically −
mysql> select * from DemoTable1526 -> order by PurchaseDate > curdate() - interval 3 month desc,CustomerName;
This will produce the following output −
+--------------+--------------+ | CustomerName | PurchaseDate | +--------------+--------------+ | Bob | 2019-12-31 | | David | 2019-10-10 | | Adam | 2019-06-01 | | Chris | 2019-05-24 | | Sam | 2019-04-26 | +--------------+--------------+ 5 rows in set (0.00 sec)