In Database Programming, you often need to store a piece of information (like a "Current Max ID" or a "Tax Rate") and use it across multiple lines of your code. MySQL provides Variables to handle this session-level state.
MySQL has two primary types of variables you will use:
| Type | Syntax | Usage |
|---|---|---|
| User-Defined | @variable_name |
Storing values during a specific session/connection. |
| System | @@variable_name |
Reading or changing server settings (e.g., @@version). |
- Parameterization: Setting a
@cutoff_dateat the top of a script and referencing it in 10 different Queries below. - Procedural Logic: Storing the count of deleted rows to use in a print statement or audit log.
- Dynamic Queries: Passing values into Stored Procedures.
User-defined variables are loosely typed and stay alive until you disconnect from MySQL.
- If you set
@x = 10in Workbench, and then 5 minutes later you runSELECT @x, it will still return 10. - If a different user connects, they cannot see your
@x. Each connection has its own "Private Memory" for variables.
There are two ways to set a variable:
-- Method 1: SET command
SET @my_var = 100;
-- Method 2: Assign inside a SELECT (Walrus Operator)
SELECT @max_val := MAX(Price) FROM Products;
-- Note: Use := for assignment inside a SELECT.SELECT * FROM Orders WHERE Amount > @max_val;System variables control how the MySQL engine behaves.
- Global: Affect the whole server (e.g.,
@@max_connections). - Session: Affect only your current connection (e.g.,
@@sql_mode).
-- Check your MySQL version
SELECT @@version;
-- Check the current timezone
SELECT @@time_zone;- Using
=instead of:=: In aSELECTstatement,=is for comparison. If you want to assign a value to a variable during a query, you MUST use:=. - Expecting variables to persist after logout: Variables are stored in RAM; they do not get saved to the database.
Default Values:
If you reference a variable that has never been set, MySQL returns NULL and does not throw an error. This can lead to silent logic bugs in your scripts. Always initialize your variables at the top of your scripts.
- Task 1: What is the difference between
@varand@@var? - Task 2: Write a script that sets a variable
@standard_taxto0.18and then uses it to calculate the tax for a product price from theProductstable.