- 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 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)
- Related Articles
- How to store query result (a single document) into a variable?
- Set the result of a query to a variable in MySQL?
- How to store Query Result in a variable using MySQL?
- How can we use SET statement to assign a SELECT result to a MySQL user variable?
- Assign an SQL result to variable from prepared statement in MySQL?
- Set user variable from result of query in MySQL?
- Store a variable with the result of a MySQL SELECT CASE?
- How to assign a reference to a variable in C#
- How to get file extension of file as a result of MySQL query?
- How to declare a variable in MySQL for a normal query?
- MySQL query to return a string as a result of IF statement?
- How can we assign a function to a variable in JavaScript?
- How do I split a numerical query result in MySQL?
- How to assign multiple values to a same variable in Python?
- How do I assign a dictionary value to a variable in Python?

Advertisements