Selecting a value in custom order from another column in a MySQL table with a single query

MySQLMySQLi Database

For this, you can use IN().

Let us first create a table:

mysql> create table DemoTable727 (
   Name varchar(100),
   Score int
);
Query OK, 0 rows affected (0.88 sec)

Insert some records in the table using insert command:

mysql> insert into DemoTable727 values('Chris',45);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable727 values('Robert',89);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable727 values('Carol',94);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable727 values('David',93);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable727 values('Mike',78);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable727 values('Sam',67);
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement:

mysql> select *from DemoTable727;

This will produce the following output -

+--------+-------+
| Name   | Score |
+--------+-------+
| Chris  | 45    |
| Robert | 89    |
| Carol  | 94    |
| David  | 93    |
| Mike   | 78    |
| Sam    | 67    |
+--------+-------+
6 rows in set (0.00 sec)

Following is the query to select a value in custom order from another column in a MySQL table with a single query:

mysql> select Score from DemoTable727 where Name IN('Robert','David','Sam');

This will produce the following output -

+-------+
| Score |
+-------+
| 89    |
| 93    |
| 67    |
+-------+
3 rows in set (0.00 sec)
raja
Published on 22-Aug-2019 07:35:16
Advertisements