MySQL Variables
MySQL provides variables that are used to store values temporarily during a session. These variables can be categorized into two main types:
1. User-Defined Variables
Definition
- User-defined variables are variables created by the user for temporary use within a session.
- These variables are session-specific and are not shared across connections.
Syntax
To define or assign a value to a user-defined variable:
To retrieve the value of a variable:
Examples
Assigning and Retrieving Values
Using Variables in Calculations
Using Variables in Queries
2. System Variables
Definition
- System variables are built-in variables that control the configuration and behavior of the MySQL server.
- They can be either global or session-specific:
- Global variables affect the entire server and all sessions.
- Session variables affect only the current session.
Syntax
To view system variables:
To set system variables:
To view specific system variables:
Examples
View All System Variables
View a Specific Variable
Set a Session Variable
Set a Global Variable
Retrieve Variable Values
Differences Between User-Defined and System Variables
Feature | User-Defined Variables | System Variables |
---|---|---|
Scope | Session-specific | Global or session-specific |
Persistence | Temporary, lasts for the session | Can be persistent (in config) |
Assignment | SET or SELECT | SET SESSION or SET GLOBAL |
Default Values | None must be explicitly set | Predefined by MySQL |
Use Cases
User-Defined Variables
- Temporary data storage for calculations or intermediate query results.
- Dynamic queries based on session-specific values.
System Variables
- Adjusting server configuration, e.g., increasing connection limits.
- Tuning performance settings, e.g., buffer sizes or cache settings.
Conclusion
MySQL variables, whether user-defined or system-level, are versatile tools for session management, query customization, and server configuration. By understanding how to use these variables, you can efficiently manage and optimize your MySQL environment.