MySQL ORDER BY with numeric user-defined variable?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1898
   (
   Number int
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1898 values(10);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(70);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(30);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(50);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(40);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1898;

This will produce the following output −

+--------+
| Number |
+--------+
|     10 |
|     70 |
|     30 |
|     50 |
|     40 |
+--------+
5 rows in set (0.00 sec)

Here is the query to perform ORDER BY with numeric user-defined variable −

mysql> set @limitValue:=1;
Query OK, 0 rows affected (0.00 sec)
mysql> set  @query:=CONCAT('select * from DemoTable1898 order by ',@limitValue);
Query OK, 0 rows affected (0.00 sec)
mysql> prepare stmt from @query;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute stmt;

This will produce the following output −

+--------+
| Number |
+--------+
|     10 |
|     30 |
|     40 |
|     50 |
|     70 |
+--------+
5 rows in set (0.00 sec)

Here is the query to deallocate the prepare query −

mysql> deallocate prepare stmt;
Query OK, 0 rows affected (0.00 sec)
raja
Published on 27-Dec-2019 07:05:19
Advertisements