How to store Query Result in a variable using MySQL?

MySQLMySQLi Database

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)
raja
Published on 10-Jan-2019 17:39:56
Advertisements