ORDER BY records in MySQL based on a condition

MySQLMySQLi Database

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)
raja
Published on 03-Oct-2019 10:18:22
Advertisements