To display a list of records in a specific order, you need to set conditions and use ORDER BY. For this, use ORDER BY CASE statement. Let us first create a table −
mysql> create table DemoTable2039 -> ( -> Name varchar(20) -> ); Query OK, 0 rows affected (0.62 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2039 values('John Doe'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable2039 values('John Smith'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable2039 values('Chris Brown'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable2039 values('Adam Smith'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable2039 values('David Miller'); Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2039;
This will produce the following output −
+--------------+ | Name | +--------------+ | John Doe | | John Smith | | Chris Brown | | Adam Smith | | David Miller | +--------------+ 5 rows in set (0.00 sec)
Here is the query to display a specific list of records in ASC order −
mysql> select *from DemoTable2039 -> order by -> case when Name like '%Smith%' then 101 -> else -> 100 -> end, -> Name;
This will produce the following output −
+--------------+ | Name | +--------------+ | Chris Brown | | David Miller | | John Doe | | Adam Smith | | John Smith | +--------------+ 5 rows in set (0.37 sec)