Select into a user-defined variable with MySQL


For user-defined variables, we use @ in MySQL. Following is the syntax. Here, @anyVariableName is our user-defined variable −

select yourColumnName into @anyVariableName from yourTableName where yourCondition;

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100)
);
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+
| Id | Name   |
+----+--------+
|  1 | Chris  |
|  2 | Robert |
|  3 | David  |
+----+--------+
3 rows in set (0.00 sec)

Following is the query to select into a user-defined variable with MySQL −

mysql> select Name into @FirstName from DemoTable where Id=3;
Query OK, 1 row affected (0.02 sec)

Let us check the value of the variable −

mysql> select @FirstName;

This will produce the following output −

+------------+
| @FirstName |
+------------+
| David      |
+------------+
1 row in set (0.00 sec)

Updated on: 01-Oct-2019

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements