✏️ Explanatory Question

What are the different types of variables in MySQL?

👁 9 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

73

What are the different types of variables in MySQL?

Level: Advanced — Understanding variable scope is key to writing correct stored programs and sessions.

MySQL supports several kinds of variables, distinguished mainly by their scope (how long they live and where they're accessible) and their prefix syntax.

The Main Variable Types

  • User-Defined (Session) Variables: Prefixed with @. Live for the entire session/connection. No declaration needed.
  • Local Variables: Declared with DECLARE inside stored programs. Exist only within that BEGIN...END block. No @ prefix.
  • System Variables: Prefixed with @@. Control server/session configuration (e.g., @@autocommit, @@version).
Key distinction: Use local variables (DECLARE) inside procedures for temporary computation, and user-defined @ variables for values that must persist across statements in a session (e.g., capturing an OUT parameter).

Variable Types Compared

Type Prefix Scope Declared?
User-Defined (Session) @ Whole session No (set on use)
Local none Inside BEGIN...END Yes (DECLARE)
System (Global) @@global. Entire server Predefined
System (Session) @@session. Current session Predefined

Quick Example

-- 1) USER-DEFINED (@) variable: persists in the session
SET @counter = 10;
SET @name = 'Rumman';
SELECT @counter + 5 AS result;    -- 15

-- Capture a query result into an @ variable
SELECT COUNT(*) INTO @total FROM employees;
SELECT @total;

-- 2) LOCAL variable: only inside a stored program
DELIMITER $$
CREATE PROCEDURE CalcBonus(IN p_id INT)
BEGIN
    DECLARE v_salary DECIMAL(10,2);     -- local, no @ prefix
    DECLARE v_bonus  DECIMAL(10,2);

    SELECT salary INTO v_salary FROM employees WHERE emp_id = p_id;
    SET v_bonus = v_salary * 0.10;

    SELECT v_salary AS salary, v_bonus AS bonus;
END $$
DELIMITER ;

-- 3) SYSTEM (@@) variable: server/session settings
SELECT @@version;                 -- MySQL version
SELECT @@autocommit;              -- current autocommit setting
SET SESSION @@autocommit = 0;     -- change for this session
Gotcha: User-defined @ variables are session-scoped and untyped — they take on the type of the last assigned value. Local DECLAREd variables are strongly typed and must be declared at the top of the block, before any statements.
Interviewer tip: The one-liner they want — "MySQL has user-defined session variables (@), local variables (DECLARE, inside stored programs), and system variables (@@ for server/session settings). Scope and typing are the key differences."