

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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 Questions & Answers
- MySQL ORDER BY with custom field value
- MySQL Order by with case?
- Set a certain value first with MySQL ORDER BY?
- MySQL order by from highest to lowest value?
- How to use ORDER BY field and sort by id in a single MySQL field?
- MySQL order by string with numbers?
- MySQL ORDER BY with EXPLAIN command
- MySQL ORDER BY strings with underscore?
- MySQL ORDER BY with CASE WHEN
- How to perform custom sort by field value in MySQL?
- ORDER BY specific field value first in MySQL
- How to ORDER BY FIELD with GROUP BY in a single MySQL query?
- How to ORDER BY LIKE in MySQL?
- How to ORDER BY RELEVANCE in MySQL?
- How to order by timestamp in MySQL?
Advertisements