Perform MySQL ORDER BY keyword match?


For this, let us create a table, insert some values and use ORDER BY CASE. Let us first create a table −

mysql> create table DemoTable602 (GameName text);
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable602 values('Candy cash game');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable602 values('Pubg');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable602 values('cash Candy game');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable602 values('subway');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable602;

This will produce the following output −

+-----------------+
| GameName        |
+-----------------+
| Candy cash game |
| Pubg            |
| cash Candy game |
| subway          |
+-----------------+
4 rows in set (0.00 sec)

Following is the query to perform MySQL ORDER BY keyword match −

mysql> select *from DemoTable602
   order by
      CASE WHEN instr(GameName, 'Candy') = 0 then 1 else 0 end,
      instr(GameName, 'cash') desc;

This will produce the following output −

+-----------------+
| GameName        |
+-----------------+
| Candy cash game |
| cash Candy game |
| Pubg            |
| subway          |
+-----------------+
4 rows in set (0.00 sec)

Updated on: 22-Aug-2019

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements