
- 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
Order by selected record in MySQL?
You can use a CASE statement for this. Let us first create a table −
mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (0.71 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values(490); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable values(310); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(540); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(123); Query OK, 1 row affected (0.60 sec) mysql> insert into DemoTable values(1230); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(1090); Query OK, 1 row affected (0.43 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select * from DemoTable;
This will produce the following output −
+--------+ | Number | +--------+ | 490 | | 310 | | 540 | | 123 | | 1230 | | 1090 | +--------+ 6 rows in set (0.00 sec)
Following is the query to order by selected record in MySQL −
mysql> select *from DemoTable order by (case when Number = 1090 then 0 else 1 end), Number;
This will produce the following output −
+--------+ | Number | +--------+ | 1090 | | 123 | | 310 | | 490 | | 540 | | 1230 | +--------+ 6 rows in set (0.00 sec)
- Related Articles
- MySQL order by 0 first and then display the record in descending order?
- Get the returned record set ordered by (ORDER BY) position in MySQL 'IN' clause
- Get the returned record set order in MySQL IN clause?
- Order date records and fetch the 2nd ordered record in MySQL
- MySQL query to fetch record by year
- Order By date ASC in MySQL?
- How to search a record by date in MySQL table?
- Resolve Syntax error near “ORDER BY order DESC” in MySQL?
- MySQL Order By specific strings?
- MySQL Order by with case?
- MySQL Order by beginning letter?
- How to ORDER BY RELEVANCE in MySQL?
- How to ORDER BY LIKE in MySQL?
- Order by last 3 chars in MySQL?
- ORDER BY a specific word in MySQL

Advertisements