How to use ORDER BY field and sort by id in a single MySQL field?

MySQLMySQLi Database

For this, you can use ORDER BY FIELD. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.78 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable values(201,'Mike');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(110,'Adam');
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable values(250,'John');
Query OK, 1 row affected (0.33 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
|  101 | Chris |
|  201 | Mike  |
|  110 | Adam  |
|  250 | John  |
+------+-------+
4 rows in set (0.00 sec)

Here is the query to use order by field as well sort by id &miuns;

mysql> select *from DemoTable
   -> order by field(Name,'Mike') desc,Id desc;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
| 201  | Mike  |
| 250  | John  |
| 110  | Adam  |
| 101  | Chris |
+------+-------+
4 rows in set (0.01 sec)
raja
Published on 13-Dec-2019 05:56:42
Advertisements