MySQL SELECT INTO Temporary Variable
MySQL SELECT INTO Temporary Variable
Summary: in this tutorial, you will learn how to use the MySQL SELECT INTO variable to
store query result in variables.
SELECT
c1, c2, c3, ...
INTO
@v1, @v2, @v3,...
FROM
table_name
WHERE
condition;
In this syntax:
c1, c2, and c3 are columns or expressions that you want to select and store into the
variables.
@v1, @v2, and @v3 are the variables which store the values from c1, c2 and c3.
The number of variables must be the same as the number of columns or expressions in the
select list. In addition, the query must returns zero or one row.
If the query return no rows, MySQL issues a warning of no data and the value of the
variables remain unchanged.
In case the query returns multiple rows, MySQL issues an error. To ensure that the query
always returns maximum one row, you use the LIMIT 1 clause to limit the result set to a
single row.
SELECT
city
INTO
@city
FROM
customers
WHERE
customerNumber = 103;
SELECT
city,
country
INTO
@city,
@country
FROM
customers
WHERE
customerNumber = 103;
The following statement shows the contents of the @city and @country variables:
SELECT
@city,
@country;
MySQL SELECT INTO variable – multiple rows example
The following statement causes an error because the query returns multiple rows:
SELECT
creditLimit
INTO
@creditLimit
FROM
customers
WHERE
customerNumber > 103;
In this tutorial, you have learned how to use the MySQL SELECT INTO variable syntax to
store result query result in one or more variables.