Syntax error Custom sorting using two different columns in MySQL?

Custom sorting using two different columns in MySQL?



For this, use ORDER BY clause along with CASE statement. Let us first create a table −

mysql> create table DemoTable1610
   -> (
   -> Marks int,
   -> Name varchar(20)
   -> ) ;
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1610 values(85,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1610 values(78,'Carol');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1610 values(78,'John');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1610 values(85,'Carol');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1610;

This will produce the following output

+-------+-------+
| Marks | Name  |
+-------+-------+
|    85 | John  |
|    78 | Carol |
|    78 | John  |
|    85 | Carol |
+-------+-------+
4 rows in set (0.00 sec)

Here is the query to custom sort using two different columns in MySQL −

mysql> select * from DemoTable1610
   -> order by Marks,case when Name='Carol' then 1 else 0 end;

This will produce the following output

+-------+-------+
| Marks | Name  |
+-------+-------+
|    78 | John  |
|    78 | Carol |
|    85 | John  |
|    85 | Carol |
+-------+-------+
4 rows in set (0.00 sec)
Updated on: 2019-12-17T06:01:17+05:30

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements