Mastering MySQL: Variables and Parameters for Enhanced Control
Owais Qayyum
PhD Scholar at UiT - Arctic University of Norway | Data Engineer (ETL, PySpark, SparkSQL, Databricks) | Databases (MySQL) | Azure Cloud (Synapse Analytics, Data Factory, Data Lake) | Python | Elixir
MySQL offers powerful mechanisms for managing data within your stored procedures and functions. This blog post dives deep into two key concepts: variables and parameters. We'll explore how to declare and use them effectively, unlocking greater control and flexibility in your database operations.
SQL Variables: Storing Values on the Fly
Variables act as temporary containers for data within your SQL statements. They come in handy when you need to:
There are two main ways to declare variables in MySQL:
1. Using SET Keyword:
The SET keyword allows you to create variables within or outside stored procedures. The syntax is straightforward:
@variable_name = value;
Example:
SET @dept_name = 'Legal';
SELECT *
FROM employees
WHERE Department = @dept_name;
This code snippet first assigns the value 'Legal' to the variable @dept_name. Then, the SELECT statement uses this variable to filter employees belonging to the Legal department.
2. Using DECLARE Keyword:
For variables within stored procedures, you can also leverage the DECLARE keyword. This approach offers additional control over data type and default values:
DECLARE variable_name DATATYPE DEFAULT value;
-- Example
CREATE PROCEDURE name_and_dept() AS
BEGIN
DECLARE dept_name VARCHAR(50) DEFAULT 'Legal';
-- Rest of your procedure logic using dept_name
SELECT employees.EmployeeName, employees.Department
FROM employees
WHERE Department = dept_name;
END;
Here, the DECLARE statement creates a variable named dept_name with a data type of VARCHAR(50) and a default value of 'Legal'. The procedure then utilizes this variable to retrieve employee names and departments.
Declaring Variables within SELECT Statements:
MySQL provides two methods to declare variables within SELECT statements:
First Way (Assignment Operator):
SELECT @value := columns;
-- Example
SELECT @max_salary := MAX(AnnualSalary) AS max_salary
FROM employees;
SELECT @max_salary;
-- This will give you the max salary
This approach assigns the maximum annual salary retrieved by the MAX function to the variable @max_salary. The subsequent SELECT statement displays the stored value.
Second Way (INTO Clause):
-- Use the INTO KEYWORD to insert the result of AVG function to
-- variable @avg_salary
SELECT AVG(AnnualSalary) INTO @avg_salary
FROM employees;
SELECT ROUND(@avg_salary, 2) AS avg_salary;
Here, the AVG function calculates the average salary and stores it directly in the variable @avg_salary using the INTO clause. The second SELECT statement rounds and displays the average salary.
领英推荐
SQL Parameters: Passing Arguments to Procedures and Functions
Parameters act as placeholders for values passed from outside your stored procedures or functions. This allows for dynamic execution based on the provided input. MySQL offers three parameter types:
1. IN Parameters:
The most common type, IN parameters, are used to pass values to the procedure. They represent a one-way flow of data, from the calling statement to the procedure.
CREATE PROCEDURE procedure_name(IN logic(value1, value2))
SELECT logic;
-- Example (assuming logic is a user-defined function)
CREATE PROCEDURE name_salary(IN salary INT)
SELECT EmployeeName, AnnualSalary
FROM employees
WHERE AnnualSalary < salary;
CALL name_salary(50000);
In this example, the name_salary procedure takes an IN parameter named salary. The calling statement (CALL) provides the value 50000, which the procedure uses to filter employees with lower salaries.
2. OUT Parameters:
OUT parameters provide a mechanism to return values from a stored procedure to the calling statement. They enable a two-way flow of data.
-- Syntax
CREATE PROCEDURE GetLowestSalary(OUT lowest_salary INT)
SELECT MIN(AnnualSalary) INTO lowest_salary
FROM employees;
CALL GetLowestSalary(@lowest);
-- you just passed a variable name in which you want to store the
-- output result
SELECT @lowest;
-- this gives you the value of the lowest_salary calculated by the
-- stored procedure
The GetLowestSalary procedure demonstrates how to use an OUT parameter. It calculates the minimum salary and stores the value in the lowest_salary variable.
3. INOUT Parameters
INOUT parameters offer a more versatile approach compared to IN and OUT parameters. They allow for both passing a value to the procedure and receiving a modified value back in the calling statement. This enables two-way data exchange.
Here's the syntax for creating a procedure with an INOUT parameter:
CREATE PROCEDURE procedure_name(INOUT variable_name DATATYPE)
-- Your procedure logic using variable_name
Example:
CREATE PROCEDURE a_squared(INOUT number INT)
BEGIN
SET number = number * number;
END;
SET @num = 5;
CALL a_squared(@num);
SELECT @num;
In this example, the a_squared procedure takes an INOUT parameter named number. The calling statement assigns the value 5 to the variable @num and then calls the procedure. Inside the procedure, the number (which refers to the same @num variable) is squared. Finally, the calling statement displays the updated value of @num, which is now 25.
Important Note:
While INOUT parameters offer flexibility, it's crucial to understand their limitations. You cannot use them solely to return a value from a procedure. As shown in the example above, the calling statement must provide an initial value for the INOUT parameter.
Here's an illustration of why using an OUT parameter is necessary for scenarios where you only want to return a value:
-- This code will give us a null value (incorrect)
CREATE PROCEDURE add_numbers(OUT x INT)
SET x = x + x + x; -- This line assumes a value has already been assigned to x, which isn't the case
SET @n = 1;
CALL add_numbers(@n);
SELECT @n;
In this example, the add_numbers procedure attempts to use an OUT parameter to store the result of tripling a value. However, since no initial value is provided for x, the calculation results in NULL. To address this, you would need to use an OUT parameter instead:
By understanding the use cases and limitations of INOUT parameters, you can effectively leverage them for scenarios requiring two-way data exchange within your stored procedures.
CREATE PROCEDURE add_numbers(OUT result INT)
SET result = @n + @n + @n; -- Assuming @n has already been assigned a value
SET @n = 1;
CALL add_numbers(@result);
SELECT @result;
This post has equipped you with a solid understanding of SQL variables and parameters in MySQL. By mastering these concepts, you can enhance the control, flexibility, and readability of your database operations.