![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use ORDER BY field and sort by id in a single MySQL field?
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)
Advertisements