Just Learn Code

Mastering User-Defined and System Variables in MySQL

How to Use User-Defined Variables in MySQL

Do you want to improve the functionality of your MySQL queries? One feature that many people overlook is the use of user-defined variables.

By using variables in your code, you can simplify your queries and even perform complex calculations. In this article, we’ll look at how to declare and use user-defined variables in MySQL.

Initializing User-Defined Variables

Before you can use a variable in your query, you need to set its value. You can do this using the SET keyword followed by the variable name and the value you want to assign.

For example, let’s say you want to store the current year in a variable called @current_year. Here’s how you would do it:


SET @current_year = YEAR(CURDATE());


In this example, the YEAR() function is used to extract the year from the current date, which is obtained using the CURDATE() function.

You can now use @current_year in your queries.

Using Variables as Fields in SELECT Statements

One common use of variables in MySQL is to store the result of a calculation and then use it in a SELECT statement. For example, let’s say you want to calculate the total revenue for your business and divide it by the number of employees.

Here’s how you can do it using variables:


SET @total_revenue = (SELECT SUM(amount) FROM sales);

SET @num_employees = (SELECT COUNT(*) FROM employees);

SELECT @total_revenue/@num_employees AS avg_revenue_per_employee;


In this example, the @total_revenue variable is set to the sum of the amount field in the sales table. The @num_employees variable is set to the number of rows in the employees table.

Finally, the SELECT statement divides @total_revenue by @num_employees and assigns it to a new field called avg_revenue_per_employee.

Declaring User-Defined Variables

In addition to initializing variables using SET, you can also declare them using the DECLARE keyword. Declare is used to create local variables that are only available within the block of code where they are defined.

For example, let’s say you want to calculate the area of a rectangle:




SELECT @width*@height AS area;


In this example, the DECLARE keyword is used to create two variables called @width and @height. Both variables are declared as integers and given default values of 5 and 10, respectively.

The variables are then used in the SELECT statement to calculate the area of the rectangle.

Declare Local Variables in MySQL

In addition to user-defined variables, MySQL also supports local variables. These are variables that are declared within a stored procedure or function and are only visible within that procedure or function.

Here’s an example of declaring and using a local variable:


CREATE PROCEDURE calculate_area(IN width INT, IN height INT)



SET area = width*height;

SELECT area;



In this example, a stored procedure called calculate_area is created. The procedure accepts two parameters, width and height.

A local variable called area is declared and set to the product of width and height. Finally, the SELECT statement returns the value of area.

Using Local Variables

Local variables can be used in much the same way as user-defined variables. They can be used to store intermediate results or perform calculations.

For example, let’s say you want to calculate the sum of the squares of two numbers:


CREATE FUNCTION sum_squares(x INT, y INT)



DECLARE x_squared INT;

DECLARE y_squared INT;

SET x_squared = x*x;

SET y_squared = y*y;

RETURN x_squared + y_squared;



In this example, a stored function called sum_squares is created. The function accepts two parameters, x and y.

Two local variables, x_squared and y_squared, are declared and set to the squares of x and y, respectively. The function then returns the sum of x_squared and y_squared.


User-defined variables and local variables are powerful features in MySQL that can help you simplify your queries and perform complex calculations. By declaring and using variables in your code, you can improve the readability and maintainability of your database applications.

Whether you’re a beginner or an experienced developer, understanding how to use variables is an essential skill for working with MySQL. Variables have always been an essential aspect of programming and database applications.

In MySQL, variables play an essential role in the application’s performance and execution. MySQL supports different types of variables, including user-defined variables and system variables.

In this article, we will delve into the types of variables in MySQL, explore how to declare system variables, and how to view system variables.

Types of Variables in MySQL

MySQL has two primary types of variables: user-defined variables and system variables. User-defined variables are declared and initialized by the users themselves to store values for later use in their queries, stored procedures, or functions.

User-defined variables start with the ‘@’ symbol, such as @num_employees. System variables, also known as global or session variables, are already declared program-wide or pre-defined in MySQL, meaning that the users cannot initialize them.

However, users can assign new values to these variables to alter the behavior of the database system or the session at hand. System variables can be classified as global system variables or session system variables.

Global system variables affect the entire MySQL server’s behavior and settings, and the changes made to them persist across the sessions. Some examples of global system variables include max_connections and innodb_buffer_pool_size.

Session system variables, on the other hand, only affect a single MySQL session. The changes made to session system variables only last for the duration of the current session, making them useful for temporary purposes.

One of the common session system variables is the sql_mode, which determines the rules governing how MySQL operates under different scenarios.

Declaring System Variables

Before working with system variables, it’s essential to understand how they are declared, set, and used. System variables are declared and set using the SET command with the GLOBAL or SESSION keyword.

To set a global system variable, use the command “SET GLOBAL variable_name = value;”. This command sets the system variable for the entire server and its sessions.

For example, let’s say you want to set the max_connections to 500, you can use the following command:


SET GLOBAL max_connections = 500;


To set a session system variable, use the command “SET SESSION variable_name = value;”. This command sets the system variable for the current session only.

Suppose you want to set the sql_mode to ‘ANSI’, you can use the following command:


SET SESSION sql_mode = ‘ANSI’;


It is crucial to note that certain system variables can only be set using either the GLOBAL or SESSION option, and trying to set them using the incorrect option results in an error.

Viewing System Variables

After declaring and setting system variables, it is important to know how to view them to ensure that the correct values have been set. MySQL provides two ways to view system variables: Using the SHOW command and querying the information_schema database.

To display all system variables, use the command “SHOW VARIABLES;”. This command lists all the system variables and their corresponding values.

To filter the results based on a specific keyword, use the LIKE operator. Suppose you only want to view system variables related to the innodb storage engine.

In that case, you can use the following command:




Alternatively, you can query the information_schema database to view system variables. Information_schema is a database in MySQL that stores metadata about all the other databases and tables in the server instance.

To display system variables using this method, use the following command:


SELECT * FROM information_schema.global_variables;


This command displays a list of all global system variables and their corresponding values, similar to the SHOW command.


MySQL system variables play an essential role in the performance and configuration of the database server. Knowing how to declare and utilize these variables can significantly affect the performance and behavior of the MySQL server.

In this article, we have discussed the types of variables in MySQL, how to declare system variables using the GLOBAL and SESSION commands, and how to view system variables using the SHOW command and querying the information_schema database. By mastering these fundamental concepts, you can make informed decisions and optimize your database applications.

In summary, MySQL allows for two types of variables: user-defined and system variables. System variables are already declared and can only be changed through setting a new value.

They can be either global or session-based. To view these variables, one can use the “SHOW” or “INFORMATION_SCHEMA” command.

Implementing these fundamental concepts can significantly influence the performance of a MySQL database and optimize query execution. Therefore, it is crucial to understand how to declare, set, and use system variables to achieve optimal server performance.

Popular Posts