Variables
So what is a variable?
A variable is a name given to data that we need to store and use in our SQL statements.
For instance, suppose we want to get all information related to employee 1 from the employees and mentorships tables. We can do that as follows:
SELECT * FROM employees WHERE id = 1;
SELECT * FROM mentorships WHERE mentor_id = 1;
SELECT * FROM mentorships WHERE mentee_id = 1;
However, if we realize that we made a mistake and want the information of employee 2 instead, we’ll have to change all the three SQL statements above. This is relatively easy for three statements, but can be a lot of trouble if there are hundreds of statements. A better way is to use variables.
To do that, we can first declare and initialize a variable using the statement below:
SET @em_id = 1;
Here, we declare a variable called @em_id. User defined variables in MySQL have to be prefixed with the @ symbol.
...