MySQL field() function?

MySQLMySQLi Database

The field() function returns the index position of a value in a list of values. Let us sort the values using field() function with ORDER BY. The syntax is as follows.

SELECT *FROM yourTableName order by
   field(yourColumnName,yourValue1,yourValue2,yourValue3,yourValue4,.....N) desc;

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

mysql> create table OrderByDemo
-> (
-> StudentId int
-> );
Query OK, 0 rows affected (0.71 sec)

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

mysql> insert into OrderByDemo values(101);
Query OK, 1 row affected (0.19 sec)

mysql> insert into OrderByDemo values(1010);
Query OK, 1 row affected (0.56 sec)

mysql> insert into OrderByDemo values(1001);
Query OK, 1 row affected (0.12 sec)

mysql> insert into OrderByDemo values(401);
Query OK, 1 row affected (0.12 sec)

Now you can display all records from the table using select statement. The query is as follows.

mysql> select *from OrderByDemo;

The following is the output.

+-----------+
| StudentId |
+-----------+
| 101       |
| 1010      |
| 1001      |
| 401       |
+-----------+
4 rows in set (0.00 sec)

Here is the query to sort order by value. We will sort in descending order. The query is as follows.

mysql> select *from OrderByDemo order by field(StudentId,101,401,1001,1010) desc;

The following is the output.

+-----------+
| StudentId |
+-----------+
| 1010      |
| 1001      |
| 401       |
| 101       |
+-----------+
4 rows in set (0.00 sec)
raja
Published on 11-Jan-2019 11:31:09
Advertisements