- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 assign the result of a MySQL query into a variable?
Use @anyVariableName to assign the result of a query into a variable. Let us first create a table −
mysql> create table DemoTable1864 ( Id int, FirstName varchar(20), LastName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1864 values(101,'Chris','Brown'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1864 values(102,'David','Miller'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1864 values(103,'Adam','Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1864 values(104,'John','Doe'); Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1864;
This will produce the following output −
+------+-----------+----------+ | Id | FirstName | LastName | +------+-----------+----------+ | 101 | Chris | Brown | | 102 | David | Miller | | 103 | Adam | Smith | | 104 | John | Doe | +------+-----------+----------+ 4 rows in set (0.00 sec)
Here is the query to assign the result of a query into a variable −
mysql> select @fName:=FirstName,@lName:=LastName from DemoTable1864 where Id=103;
This will produce the following output −
+-------------------+------------------+ | @fName:=FirstName | @lName:=LastName | +-------------------+------------------+ | Adam | Smith | +-------------------+------------------+ 1 row in set (0.00 sec)
Advertisements