How to arrange data in s specific order in MySQL?



Use ORDER BY IF() to arrange data in a specific order. Following is the syntax −

select *from yourTableName ORDER BY IF(yourColumnName=yourValue1 OR
yourColumnName=yourValue2 OR yourColumnName=yourValue3,yourColumnName,
~yourColumnName) ASC;

Let us first create a table −

mysql> create table arrangeDataInSpecificOrder
   -> (
   -> StudentId int,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.64 sec)

Following is the query to insert some records in the table using insert command −

mysql> insert into arrangeDataInSpecificOrder values(10,'Larry');
Query OK, 1 row affected (0.12 sec)
mysql> insert into arrangeDataInSpecificOrder values(15,'Mike');
Query OK, 1 row affected (0.09 sec)
mysql> insert into arrangeDataInSpecificOrder values(100,'Sam');
Query OK, 1 row affected (0.16 sec)
mysql> insert into arrangeDataInSpecificOrder values(70,'Carol');
Query OK, 1 row affected (0.12 sec)
mysql> insert into arrangeDataInSpecificOrder values(90,'Bob');
Query OK, 1 row affected (0.14 sec)
mysql> insert into arrangeDataInSpecificOrder values(300,'David');
Query OK, 1 row affected (0.12 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from arrangeDataInSpecificOrder;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 10        | Larry       |
| 15        | Mike        |
| 100       | Sam         |
| 70        | Carol       |
| 90        | Bob         |
| 300       | David       |
+-----------+-------------+
6 rows in set (0.00 sec)

Here is the query to arrange data in specific order −

mysql> select * from arrangeDataInSpecificOrder ORDER BY IF(StudentId=300 OR
StudentId=100 OR StudentId=10,StudentId, ~StudentId) ASC;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 10        | Larry       |
| 100       | Sam         |
| 300       | David       | 
| 90        | Bob         |
| 70        | Carol       |
| 15        | Mike        |
+-----------+-------------+
6 rows in set (0.00 sec)

Advertisements