Variables are used to store values temporarily during the execution of SQL queries. There are two main types of variables in MySQL:
- Session Variables: Session variables are user-defined and can be used across the session. They do not need to be declared; they are created when first assigned a value. They are prefixed with an
@symbol. - Local Variables: These are variables that are declared within a block of SQL code (like within a stored procedure, function, or trigger) and are not prefixed with
@. They need to be declared with a data type.
# Session Variables:
SET @myVariable = 10;
SELECT @myVariable + 5 as output; -- Output will be 15
SELECT 15 INTO @B;
Select @B as output; -- Output will be 15
# Local Variables:
DELIMITER $$
CREATE PROCEDURE CalculateTotal(IN price DECIMAL(10, 2), IN quantity INT)
BEGIN
DECLARE total DECIMAL(10, 2);
SET total = price * quantity;
SELECT total AS TotalPrice;
END$$
DELIMITER ;
call CalculateTotal(10,20); --output will be 200.00