MySQL
Variable Declaration
SQL Programming
Database Management
Tutorial

How to declare a variable in MySQL?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

In MySQL, declaring and using variables is a fundamental aspect of writing efficient and organized SQL scripts. Variables allow you to store and manipulate values temporarily within a session, making it easier to manage data processing within stored procedures, functions, and scripts. In this article, we'll explore how to declare and use different kinds of variables in MySQL through technical explanations and examples.

Types of Variables in MySQL

MySQL supports different types of variables, each serving different purposes and usage scenarios. These are:

  1. User-Defined Variables: Variables that are session-specific and can be used without prior declaration.
  2. Local Variables: Variables that are declared within a stored procedure and have a limited scope.
  3. System Variables: Built-in variables that are used to configure the MySQL server.

User-Defined Variables

Characteristics

  • User-defined variables are session-specific, meaning they are available only in the current session.
  • They are not case-sensitive and can be used without declaring them beforehand.
  • These variables are denoted by the @ prefix.

How to Use

You can assign values to user-defined variables using the := operator. These values can be from direct assignments, query results, or expressions. Here is an example:

sql
SET @total_sales := 1000;
SELECT @total_sales := @total_sales + 500;
SELECT @total_sales; -- Outputs 1500

Caveats

User-defined variables may behave unpredictably if not assigned correctly, especially when used within complex queries.

Local Variables

Characteristics

  • Local variables need to be declared using the DECLARE statement.
  • They are only available within the stored procedure in which they are declared and lose their values once the procedure ends.

How to Declare and Use

To declare a local variable, use the DECLARE statement followed by a datatype, and optionally, a default value.

sql
1DELIMITER //
2
3CREATE PROCEDURE calculateSum()
4BEGIN
5    DECLARE sum INT DEFAULT 0;
6    DECLARE num1 INT DEFAULT 100;
7    DECLARE num2 INT DEFAULT 200;
8    
9    SET sum = num1 + num2;
10    SELECT sum;
11END //
12
13DELIMITER ;
14CALL calculateSum(); -- Outputs 300

System Variables

Characteristics

  • System variables are used for server settings and configurations.
  • They have a global scope or can be session-specific.

How to Use

Access and modify system variables using the SET statement. Some system variables can be under two scopes: session-level and global-level. You can assign values by specifying the desired scope:

sql
SHOW VARIABLES LIKE 'max_connections';
SET GLOBAL max_connections = 200;
SET SESSION max_allowed_packet = 16384;

Summary Table of MySQL Variables

Variable TypeScopeDeclaration RequiredCan Be Set DynamicallyUse Case
User-Defined VariablesSessionNoYesTemporary storage within sessions and result set iterations
Local VariablesProcedureYesNoTemporary storage and manipulation within stored procedures and functions
System VariablesGlobal/SessionNoYesServer configurations and session settings

Additional Details

Best Practices for Using Variables

  • Naming: Use clear and descriptive names for variables to avoid conflicts and enhance readability.
  • Scope Control: Understand the variable's scope—session, process, or global—to prevent unintended side effects.
  • Type Safety: Ensure that variable types are selected appropriately to handle expected data values and ranges.

Conclusion

Understanding and effectively using variables in MySQL is crucial for the dynamic handling of data within SQL scripts and procedural programming. Each type of variable serves distinct roles and is suited for particular use cases, from simple calculations in user-defined variables to more complex data handling within stored procedures using local variables. Utilize system variables wisely to manage server configurations adeptly.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.