ORDER BY a specific word in MySQL

MySQLMySQLi Database

For this, use ORDER BY INSTR(). Let us first create a table −

mysql> create table DemoTable822(Word text);
Query OK, 0 rows affected (1.11 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable822 values('Forever');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable822 values('ever');
Query OK, 1 row affected (1.31 sec)
mysql> insert into DemoTable822 values('every');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable822 values('everyday');
Query OK, 1 row affected (0.58 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable822;

This will produce the following output −

+----------+
| Word     |
+----------+
| Forever  |
| ever     |
| every    |
| everyday |
+----------+
4 rows in set (0.00 sec)

Following is the query to order by a specific word in the beginning or inside a string −

mysql> select *from DemoTable822 where Word LIKE '%ever%'
   order by INSTR(Word, 'ever'), Word;

This will produce the following output −

+----------+
| Word     |
+----------+
| ever     |
| every    |
| everyday |
| Forever  |
+----------+
4 rows in set (0.00 sec)
raja
Published on 03-Sep-2019 15:23:51
Advertisements