

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Storing value from a MySQL SELECT statement to a variable?
Let us first create a table −
mysql> create table DemoTable631 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentName varchar(100) ); Query OK, 0 rows affected (0.83 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable631(StudentName) values('John Smith'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable631(StudentName) values('Adam Smith'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable631(StudentName) values('David Miller'); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable631;
This will produce the following output −
+-----------+--------------+ | StudentId | StudentName | +-----------+--------------+ | 1 | John Smith | | 2 | Adam Smith | | 3 | David Miller | +-----------+--------------+ 3 rows in set (0.00 sec)
Following is the query to store value from select to a variable −
mysql> set @fullName=(select StudentName from DemoTable631 where StudentId=2); Query OK, 0 rows affected (0.00 sec)
Now you can display the value of a variable −
mysql> select @fullName;
This will produce the following output −
+------------+ | @fullName | +------------+ | Adam Smith | +------------+ 1 row in set (0.00 sec)
- Related Questions & Answers
- How to select return value from MySQL prepared statement?
- Change value from 1 to Y in MySQL Select Statement?
- MySQL case statement inside a select statement?
- How can we use SET statement to assign a SELECT result to a MySQL user variable?
- Change value from 1 to Y in MySQL Select Statement using CASE?
- IF() function in a MySQL Select statement?
- Set MySQL select in a custom variable
- Select into a user-defined variable with MySQL
- MySQL select only a single value from 5 similar values?
- Add a percentage (%) sign at the end to each value while using MySQL SELECT statement
- Is there any way to use values from a JSON object in a MySQL Select statement?
- MySQL procedure to display a “select” statement twice
- How to use a select statement while updating in MySQL?
- Adding integers from a variable to a MySQL column?
- Assign an SQL result to variable from prepared statement in MySQL?
Advertisements