Syntax error Order by multiple columns not working as expected in MySQL?

Order by multiple columns not working as expected in MySQL?



Following is the syntax to order by multiple columns −

select *from yourTableName
order by yourColumnName1 DESC,yourColumnName2,yourColumnName3;

Let us create a table −

mysql> create table demo29
−> (
−> value1 int,
−> value2 int
−> );
Query OK, 0 rows affected (1.67 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo29 values(10,500);
Query OK, 1 row affected (0.15 sec)

mysql> insert into demo29 values(14,400);
Query OK, 1 row affected (0.14 sec)

mysql> insert into demo29 values(9,500);
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo29 values(13,400);
Query OK, 1 row affected (0.11 sec)

mysql> insert into demo29 values(45,500);
Query OK, 1 row affected (0.14 sec)

mysql> insert into demo29 values(11,400);
Query OK, 1 row affected (0.10 sec)

Display records from the table using select statement −

mysql> select *from demo29;

This will produce the following output −

+--------+--------+
| value1 | value2 |
+--------+--------+
|     10 |    500 |
|     14 |    400 |
|      9 |    500 |
|     13 |    400 |
|     45 |    500 |
|     11 |    400 |
+--------+--------+
6 rows in set (0.00 sec)

Following is the query to order by multiple columns −

mysql> select *from demo29
−> order by value2 desc,value1;

This will produce the following output −

+--------+--------+
| value1 | value2 |
+--------+--------+
|      9 |    500 |
|     10 |    500 |
|     45 |    500 |
|     11 |    400 |
|     13 |    400 |
|     14 |    400 |
+--------+--------+
6 rows in set (0.00 sec)
Updated on: 2020-11-19T12:25:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements