MySQL Order By specific strings?

MySQLMySQLi Database

Order by the choice of strings you want, using the FIELD() function. The syntax is as follows −

SELECT *FROM yourTableName
ORDER BY FIELD(yourColumnName,’yourValue1’, ’yourValue2’,’yourValue3’,....N);

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table OrderByListOfStrings
   -> (
   -> Id int not null auto_increment,
   -> CarName varchar(20),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.68 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into OrderByListOfStrings(CarName) values('Ford');
Query OK, 1 row affected (0.18 sec)

mysql> insert into OrderByListOfStrings(CarName) values('Audi');
Query OK, 1 row affected (0.17 sec)

mysql> insert into OrderByListOfStrings(CarName) values('Honda');
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByListOfStrings(CarName) values('Aston Martin');
Query OK, 1 row affected (0.53 sec)

mysql> insert into OrderByListOfStrings(CarName) values('Bugatti');
Query OK, 1 row affected (0.20 sec)

mysql> insert into OrderByListOfStrings(CarName) values('BMW');
Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from OrderByListOfStrings;

The following is the output −

+----+--------------+
| Id | CarName      |
+----+--------------+
|  1 | Ford         |
|  2 | Audi         |
|  3 | Honda        |
|  4 | Aston Martin |
|  5 | Bugatti      |
|  6 | BMW          |
+----+--------------+
6 rows in set (0.00 sec)

Here is the query to get the order by the choice of strings. Set in whatever order you want them −

mysql> select *from OrderByListOfStrings
   -> order by field(CarName,'Bugatti','BMW','Audi','Aston Martin','Ford','Honda');

The following is the output that rearranges string set with field() method −

+----+--------------+
| Id | CarName      |
+----+--------------+
|  5 | Bugatti      |
|  6 | BMW          |
|  2 | Audi         |
|  4 | Aston Martin |
|  1 | Ford         |
|  3 | Honda        |
+----+--------------+
6 rows in set (0.00 sec)
raja
Published on 31-Jan-2019 16:12:46
Advertisements