How to declare and use variables in MySQL
In this tutorial article, we will explain how to declare variables in SQL code for MySQL database.
In SQL scripts, you can use variables to store values and use them in place of literals during the execution of a series of commands.
User-defined variables in MySQL
MySQL recognizes different types of variables. The first type is user-defined variables, @
identified by a symbol as a prefix. In MySQL, you can access user-defined variables without declaring or initializing them first. If you do this, the variable is assigned a NULL value when initialized. For example, if you use a variable SELECT
without assigning it a value, as in this case.
SELECT @SomeVariable;
MySQL will return a NULL value.
Initialize user-defined variables
To initialize a user defined variable, you need to use the <init> SET
or SELECT
<value> statement. You can initialize many variables at once by separating each assignment statement with a comma as shown below.
SET @FirstVar=1, @SecondVar=2;
Once you assign a value to a variable, it will have a type based on the value given. In the previous example, the types of @FirstVar
and @SecondVar
are int
.
The lifecycle of a user-defined variable lasts as long as the session is active, and it is not visible to other sessions. Once the session is closed, the variable disappears.
There are 5 data types that can be assigned to user-defined variables.
- String (binary or non-binary
- Integer
- Decimal
- floating point
NULL
, which can be associated with any type.
To assign a value to a variable, you can use the symbols =
or :=
. The following two statements have the same effect.
SET @MyIntVar = 1;
SET @MyIntVar := 1;
SELECT
Use variables as fields in a statement
Variables can be SELECT
part of the fields list of a select statement. When you specify fields in a select, you can mix variables and field names, as in this example.
SET @IndexVar := 1;
SELECT @IndexVar, ISBN FROM Books;
Declaring local variables in MySQL
Local variables do not require a prefix in their names @
, but they must be declared before they are used. To declare a local variable, you can use DECLARE
the statement, or STORED PROCEDURE
use it as a parameter in a declaration.
When you declare a local variable, you can choose to assign it a default value. If you do not assign any default value, then the variable will be initialized to a NULL value.
Every variable lives in a scope, BEGIN ... END
defined by the block containing its declaration.
The following examples illustrate two different ways of using local variables: as procedure parameters and as variables inside a procedure.
DELIMITER $$
CREATE PROCEDURE GetUpdatedPrices(itemcount INT)
BEGIN
DECLARE factor DECIMAL(5, 2);
SET factor:=3.45;
SELECT PartNo, Description, itemcount * factor * ListPrice FROM Catalogue;
END
$$
DELIMITER ;
In the previous example, the variable itemcount
is used as a parameter to pass the value to the procedure. SELECT
The variable is then used in the statement to multiply the field obtained from the table ListPrice
. The local variable factor
is used to store a decimal value that is multiplied to obtain the price.
Declaring system variables in MySQL
There is a third type of variable called a system variable, which is used to store values (variables) that affect a single client connection or values ( variables) SESSION
that affect the operation of the server as a whole .GLOBAL
System variables are normally set at server startup. To do this, you can use the command line or include SET
statements in option files. However, their values can be modified in SQL scripts.
System variables can be identified by using a double @
-sign prefix or SET
by using the words GLOBAL
or in an IN statement. Another way to distinguish between and system variables is to use a second prefix: or . The following are some examples of how to assign values to system variables.SESSION
GLOBAL
SESSION
global
session
-- Alternative ways to set session system variables:
SET interactive_timeout=30000;
SET SESSION interactive_timeout=30000;
SET @@interactive_timeout=30000;
SET @@local.interactive_timeout=30000;
-- Alternative ways to set global system variables:
SET @@global.interactive_timeout=30000;
SET GLOBAL interactive_timeout=30000;
To view the system variables used in your session or server, use SHOW VARIABLES
the statement. If you want to get the value of some specific variable, you can add a comparison operator to filter the list. For example:
SHOW VARIABLES LIKE '%timeout%'
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Running PHP on Mac
Publish Date:2025/04/12 Views:183 Category:PHP
-
In this article, we'll show you how to run PHP on your Mac. php -S Run PHP on Mac using command PHP is a server-side language. It runs on a server. Therefore, it requires a web server to run. There are different web servers like Apache HTTP
If ELSE in MySQL
Publish Date:2025/04/11 Views:85 Category:MySQL
-
In this tutorial, we aim to explore how to use IF ELSE the statement in MySQL. One of the key roles of a data analyst is to gather insights from the data and produce meaningful results. It can be done with the help of several data filtering
DATETIME vs. TIMESTAMP in MySQL
Publish Date:2025/04/11 Views:117 Category:MySQL
-
DATETIME and TIMESTAMP are two different data types that can be used to store values that must contain both a date and a time portion. In this article, we will understand how it is stored in the database and the memory required for ea
Execute multiple joins in one query in MYSQL
Publish Date:2025/04/11 Views:94 Category:MySQL
-
Have you ever wondered how to include multiple joins in one query in MySQL? You have come to the right place. Remember that joins allow us to access information from other tables. This information is included separately to avoid redundancy.
Joining 3 tables in MySQL
Publish Date:2025/04/11 Views:187 Category:MySQL
-
In this tutorial, we will learn how to join three tables in MySQL. Businesses and organizations may have to visualize three tables simultaneously based on certain matching columns common to all three tables. This operation is allowed in MyS
Use of UPDATE JOIN in MySQL
Publish Date:2025/04/11 Views:85 Category:MySQL
-
This tutorial will explain how to use the statement in MySQL database UPDATE JOIN . We generally use joins to iterate over the rows in a particular table which may or may not have similar rows in other tables. We can UPDATE use JOIN the cla
How to use the Row_Number() function in MySQL
Publish Date:2025/04/11 Views:142 Category:MySQL
-
In this tutorial, we will explain how to use the VALUES function in MySQL ROW_NUMBER() . This is a sorting method that assigns consecutive numbers within a partition starting from 1. It is important to note that no two rows within a partiti
Multiple primary keys in MySQL
Publish Date:2025/04/11 Views:66 Category:MySQL
-
In this tutorial, our goal is to explore the concept of multiple primary keys for a table in MySQL. Many times, businesses and organizations have to assign certain columns as primary keys. This primary key has multiple uses and reasons to b
Displaying foreign keys in MySQL
Publish Date:2025/04/11 Views:55 Category:MySQL
-
In this tutorial, we aim to explore how to display foreign keys for tables and columns in MySQL. The type of key that references a primary key, also known as the primary key of another table, is called a foreign key. Understanding the forei