How to assign a value in a variable in mysql

Easy Solution Web : MySQL Tutorials

First lets take a look at how can we define a variable in mysql

To define a varible in mysql
it should start with ‘@’  like @{variable_name} and this ‘{variable_name}’, we can replace it with our variable name.

Now, how to assign a value in a variable in mysql. For this we have many ways to do that

1. Using keyword ‘SET’.

Example :-
mysql >  SET @a = 1;

2. Without using keyword ‘SET’ and using ‘:=’.

mysql > @a:=1;

3. By using ‘SELECT’ statement.

mysql > select 1 into @a;

Here @a is user defined variable and 1 is going to be assigned in @a.

Now how to get or select the value of @{variable_name}.

we can use select statement like

Example :-
mysql > select @a;

it will show the output and show the value of @a.

Now how to assign a value from a table in a variable.

For this we can use two statement like :-

1. @a := (select emp_name from employee where emp_id = 1);
2. select emp_name into @a from employee where emp_id = 1;

Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.