
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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)
Advertisements