
- 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
ORDER BY records in MySQL based on a condition
For this, you can use ORDER BY IF(). Let us first create a table −
mysql> create table DemoTable ( Name varchar(50), Score int ); Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris',98); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('David',45); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Bob',56); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Sam',89); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Carol',78); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 98 | | David | 45 | | Bob | 56 | | Sam | 89 | | Carol | 78 | +-------+-------+ 5 rows in set (0.00 sec)
Following is the query to order records in MySQL based on a condition −
mysql> select *from DemoTable order by if(Name='Sam',1,0) ASC,Score DESC;
This will produce the following output −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 98 | | Carol | 78 | | Bob | 56 | | David | 45 | | Sam | 89 | +-------+-------+ 5 rows in set (0.00 sec)
- Related Questions & Answers
- Find MongoDB records based on a condition?
- SUM a column based on a condition in MySQL
- Replace records based on conditions in MySQL?
- MySQL query to get result by month and year based on condition?
- MySQL ORDER BY 'ENUM' type value based on conditions
- MySQL query to update different fields based on a condition?
- Change string based on a condition - JavaScript
- MySQL query to ORDER BY records on the basis of modulus result
- Order by on a specific number in MySQL?
- Delete only some rows from a table based on a condition in MySQL
- Implement ORDER BY in MySQL to order records in human readable format?
- MySQL update a column with an int based on order?
- Reorder array based on condition in JavaScript?
- MySQL to fetch records based on a specific month and year?
- Display records from two columns based on comparison in MySQL?
Advertisements