- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to store Query Result in a variable using MySQL?
To store query result in a variable with MySQL, use the SET command. The syntax is as follows −
SET @anyVariableName = ( yourQuery);
To understand the above concept, let us create a table. The following is the query to create a table −
mysql> create table QueryResultDemo −> ( −> Price int −> ); Query OK, 0 rows affected (0.59 sec)
Now let us insert some records into the table. The following is the query to insert records −
mysql> insert into QueryResultDemo values(100); Query OK, 1 row affected (0.17 sec) mysql> insert into QueryResultDemo values(20); Query OK, 1 row affected (0.13 sec) mysql> insert into QueryResultDemo values(200); Query OK, 1 row affected (0.10 sec) mysql> insert into QueryResultDemo values(80); Query OK, 1 row affected (0.15 sec)
Display all records from the table with the help of select statement. The query to display all records is as follows −
mysql> select *from QueryResultDemo;
The following is the output −
+-------+ | Price | +-------+ | 100 | | 20 | | 200 | | 80 | +-------+ 4 rows in set (0.00 sec)
Now you can set the query result in a variable with the help of SET command. The query is as follows.
mysql> Set @TotalPrice = (select sum(Price) from QueryResultDemo); Query OK, 0 rows affected (0.00 sec)
Check what is the value stored in variable “TotalPrice”, using the SELECT statement −
mysql> select @TotalPrice;
The following is the output −
+-------------+ | @TotalPrice | +-------------+ | 400 | +-------------+ 1 row in set (0.00 sec)
- Related Articles
- How to store query result (a single document) into a variable?
- How to assign the result of a MySQL query into a variable?
- Set the result of a query to a variable in MySQL?
- Store a variable with the result of a MySQL SELECT CASE?
- Set user variable from result of query in MySQL?
- How to declare a variable in MySQL for a normal query?
- How do I split a numerical query result in MySQL?
- How to store MongoDB result in an array?
- How can I display MySQL query result vertically?
- How can we use SET statement to assign a SELECT result to a MySQL user variable?
- How to get file extension of file as a result of MySQL query?
- Assign an SQL result to variable from prepared statement in MySQL?
- How to write a valid MySQL query and update with a custom variable?
- MySQL query to return a string as a result of IF statement?
- MySQL query to get result from multiple select statements?

Advertisements