

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL ORDER BY with numeric user-defined variable?
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)
- Related Questions & Answers
- Select into a user-defined variable with MySQL
- Perform MySQL SELECT INTO user-defined variable
- In MySQL, why a client cannot use a user-defined variable defined by another client?
- Set user-defined variable with table name in MySQL prepare statement?
- Set custom messages by working with MySQL IF Statements and SELECT in a user-defined variable
- Updating a MySQL table row column by appending a value from user defined variable?
- MySQL CREATE USER with a variable?
- Using User-Defined Variables in MySQL
- MongoDB query to set user defined variable into query?
- How Can we permanently define user-defined variable for a client in MySQL?
- How can we store a value in user-defined variable?
- MySQL Order by with case?
- User-defined Exceptions in C# with Example
- User-defined Exceptions in Python with Examples
- Increment multiple Timestamp values by setting the incremented value in a user-defined variable in SQL
Advertisements