MySQL temporary variable assignment?


You can use SET command for temporary variable assignment.

The syntax is as follows

SET @anyVariableName=(SELECT yourColumnName FROM yourTableName WHERE yourCondition);

To understand the above syntax, let us create a table. The query to create a table is as follows

mysql> create table tempVariableAssignment
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (0.59 sec)

Now insert some records in the table using insert command

mysql> insert into tempVariableAssignment(Name,Age) values('John',25);
Query OK, 1 row affected (0.14 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Carol',26);
Query OK, 1 row affected (0.17 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Sam',28);
Query OK, 1 row affected (0.13 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('David',19);
Query OK, 1 row affected (0.19 sec)
mysql> insert into tempVariableAssignment(Name,Age) values('Bob',23);
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from tempVariableAssignment;

The following is the output

+----+-------+------+
| Id | Name   Age   |
+----+-------+------+
| 1 | John   | 25   |
| 2 | Carol  | 26   |
| 3 | Sam    | 28   |
| 4 | David  | 19   |
| 5 | Bob    | 23   |
+----+-------+------+
5 rows in set (0.00 sec)

Here is the query for MySQL temporary variable assignment

mysql> set @findAge=(select Age from tempVariableAssignment where Id=4);
Query OK, 0 rows affected (0.02 sec)

Display the value of variable @findAge.

The query is as follows

mysql> select @findAge;

The following is the output

+----------+
| @findAge |
+----------+
| 19       |
+----------+
1 row in set (0.01 sec)

Here is an alternate query

mysql> select Age INTO @anotherAge
-> from tempVariableAssignment where Id=4;
Query OK, 1 row affected (0.00 sec)

Display the value of variable @anotherAge.

The query is as follows

mysql> select @anotherAge;

The following is the output

+-------------+
| @anotherAge |
+-------------+
| 19          |
+-------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements