
- 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 sort by value with MySQL ORDER BY?
For this, use the ORDER BY clause. Let us first create a table −
mysql> create table DemoTable ( StudentId int ); Query OK, 0 rows affected (0.59 sec)
Now you can insert some records in the table using insert command −
mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(60); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(70); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(45); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(55); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(78); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+-----------+ | StudentId | +-----------+ | 100 | | 60 | | 70 | | 45 | | 55 | | 78 | +-----------+ 6 rows in set (0.00 sec)
Following is the query to sort by value with ORDER BY. Here, first we are displaying 70, since we have set its order with ORDER BY. Rest of the ids are displayed in ascending order −
mysql> select *from DemoTable order by StudentId=70 desc,StudentId asc;
Output
+-----------+ | StudentId | +-----------+ | 70 | | 45 | | 55 | | 60 | | 78 | | 100 | +-----------+ 6 rows in set (0.00 sec)
- Related Articles
- MySQL ORDER BY with custom field value
- Set a certain value first with MySQL ORDER BY?
- How to use ORDER BY field and sort by id in a single MySQL field?
- How to perform custom sort by field value in MySQL?
- MySQL order by from highest to lowest value?
- MySQL Order by with case?
- Sort by date & time in descending order in MySQL?
- How to ORDER BY FIELD with GROUP BY in a single MySQL query?
- MySQL ORDER BY strings with underscore?
- MySQL ORDER BY with CASE WHEN
- MySQL order by string with numbers?
- MySQL ORDER BY with EXPLAIN command
- How to write PHP script by using ORDER BY clause inside it to sort the data of MySQL table?
- How to order by the highest value from two columns in MySQL?
- ORDER BY specific field value first in MySQL

Advertisements