Back to all posts

Variables In MySQL

Variables are used to store values temporarily during the execution of SQL queries. There are two main types of variables in MySQL: Session Variables : Ses…

Variables are used to store values temporarily during the execution of SQL queries. There are two main types of variables in MySQL:

  1. 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.
  2. 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.
SQL
# 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
SQL
# 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 

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.