MySQL query to ORDER BY `user_id` IN (1,2,3) AND `name` for custom ordering


To implement IN() for custom ordering, use ORDER BY CASE.

Let us first create a table −

mysql> create table DemoTable752 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100)
);
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable752(Name) values('John');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable752(Name) values('Carol');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable752(Name) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable752(Name) values('Mike');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable752(Name) values('Sam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable752(Name) values('Adam');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable752(Name) values('Chris');
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable752;

This will produce the following output -

+----+-------+
| Id | Name  |
+----+-------+
|  1 | John  |
|  2 | Carol |
|  3 | Bob   |
|  4 | Mike  |
|  5 | Sam   |
|  6 | Adam  |
|  7 | Chris |
+----+-------+
7 rows in set (0.00 sec)

Following is the query to order by with custom values −

mysql> select *from DemoTable752
   order by
      case
         when Id IN (1,2,3) then 1
         else Id
   END,
Name;

This will produce the following output -

+----+-------+
| Id | Name  |
+----+-------+
|  3 | Bob   |
|  2 | Carol |
|  1 | John  |
|  4 | Mike  |
|  5 | Sam   |
|  6 | Adam  |
|  7 | Chris |
+----+-------+
7 rows in set (0.00 sec)

Updated on: 03-Sep-2019

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements