
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
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)
- Related Articles
- How to ORDER BY FIELD with GROUP BY in a single MySQL query?
- Order by a single field and display rest of the records in the same order with MySQL
- How to perform custom sort by field value in MySQL?
- MySQL ORDER BY with custom field value
- MySQL order by field using CASE Statement
- ORDER BY specific field value first in MySQL
- MySQL ORDER BY Date field not in date format?
- Simulating MySQL's ORDER BY FIELD() in PostgreSQL?
- MySQL query to perform sort order on same field
- MySQL IF/WHEN/ELSE/OR with ORDER BY FIELD
- How to sort by value with MySQL ORDER BY?
- How to order last 5 records by ID in MySQL
- MySQL query to select distinct order by id
- MySQL increment a database field by 1?
- How to use union and order by clause in MySQL?

Advertisements