Variables are the backbone of dynamic, reusable, and procedural SQL code. Unlike columns in a table, variables exist only in memory during the execution of a batch or routine, acting as temporary placeholders for data values. Whether you are writing a complex stored procedure, a batch script for maintenance, or simply testing logic in an ad-hoc query, understanding how to declare and set variable in SQL is a fundamental skill. Mastering their syntax nuances across different database engines—specifically T-SQL (SQL Server), MySQL, PostgreSQL, and Oracle—allows developers to write portable, efficient, and maintainable code Practical, not theoretical..
Understanding SQL Variables: Scope and Lifetime
Before diving into syntax, it is crucial to grasp the concept of scope. A variable’s scope defines where in the code it can be referenced. In most SQL dialects, variables are local to the batch, stored procedure, function, or trigger where they are defined. They are created upon declaration and destroyed automatically when the execution context ends That's the part that actually makes a difference. Still holds up..
Counterintuitive, but true.
Variables hold a single scalar value of a specific data type (e.Now, , INT, VARCHAR, DATETIME, DECIMAL). So they cannot hold result sets (rows and columns) like a table variable or temporary table, though some modern engines allow JSON or XML types for complex structures. Think about it: g. The lifecycle is simple: Declare $\rightarrow$ Initialize/Assign $\rightarrow$ Use $\rightarrow$ Destroy.
Declaring Variables: Syntax Across Major Dialects
The DECLARE statement is the universal starting point, but the syntax varies significantly between vendors.
T-SQL (Microsoft SQL Server / Azure SQL)
In T-SQL, variable names must begin with the @ symbol. You can declare multiple variables of the same type in a single statement, separated by commas Simple, but easy to overlook..
-- Single declaration
DECLARE @EmployeeCount INT;
-- Multiple declarations, same type
DECLARE @FirstName VARCHAR(50), @LastName VARCHAR(50);
-- Declaration with specific precision
DECLARE @Salary DECIMAL(10, 2);
MySQL
MySQL uses the @ symbol for user-defined session variables (loosely typed, persist for the session) and no symbol for local variables inside stored programs (strongly typed, require DECLARE inside a BEGIN ... END block) Not complicated — just consistent..
Local Variables (Inside Routines):
DECLARE var_id INT DEFAULT 0;
DECLARE var_name VARCHAR(100) DEFAULT 'Unknown';
Note: In MySQL, DECLARE is only valid inside a BEGIN ... END compound statement (stored procedures, functions, triggers).
Session Variables (Ad-hoc/Scripts):
SET @session_var = 'Value'; -- Implicit declaration
PostgreSQL (PL/pgSQL)
PostgreSQL does not support variable declaration in plain SQL (DO blocks or scripts require the procedural language PL/pgSQL). Variables are declared in the DECLARE section of a block, without any prefix symbol.
DO $
DECLARE
v_counter INTEGER := 0;
v_message TEXT := 'Hello';
BEGIN
-- Logic here
END $;
Oracle (PL/SQL)
Oracle requires a declaration section in an anonymous block, procedure, or function. Variables are defined with the variable name followed by the data type. The %TYPE attribute is a powerful feature for anchoring types to table columns That's the whole idea..
DECLARE
v_emp_id employees.employee_id%TYPE; -- Anchored to table column
v_dept_name VARCHAR2(50) := 'Sales'; -- Initialization
BEGIN
NULL;
END;
/
Assigning Values: SET vs. SELECT
Once declared, a variable is NULL until assigned a value. Plus, the two primary methods are SET and SELECT. Choosing between them impacts performance, readability, and error handling Practical, not theoretical..
The ANSI Standard: SET
SET is the ANSI SQL standard for variable assignment. It assigns a value to one variable at a time.
Pros:
- Standard compliant (portable).
- Raises an error if the query returns multiple rows (safety net).
- Returns
NULLif the query returns zero rows (explicit behavior).
Cons:
- Cannot assign multiple variables in a single statement (in most dialects).
- Slightly more verbose for multiple assignments.
-- T-SQL Example
DECLARE @TotalSales MONEY;
SET @TotalSales = (SELECT SUM(Amount) FROM Sales WHERE Year = 2023);
-- Assigning multiple variables requires multiple SET statements
SET @Var1 = 10;
SET @Var2 = 20;
The Vendor Extension: SELECT
SELECT allows assigning values to multiple variables simultaneously from a single row source. This is often faster because it reduces the number of table scans or query executions Small thing, real impact. Practical, not theoretical..
Pros:
- Assigns multiple variables in one pass.
- Can populate variables directly from columns without scalar subqueries.
- Often faster for complex logic involving the same table.
Cons:
- Non-standard behavior across engines.
- Critical Risk: If the query returns multiple rows,
SELECTassigns the value from the last row processed silently (no error in SQL Server/MySQL), potentially hiding bugs. If it returns zero rows, the variable retains its previous value (does not reset toNULL).
-- T-SQL: Assigning multiple variables at once
DECLARE @MaxPrice MONEY, @MinPrice MONEY, @AvgPrice MONEY;
SELECT
@MaxPrice = MAX(Price),
@MinPrice = MIN(Price),
@AvgPrice = AVG(Price)
FROM Products;
-- MySQL (Session variables)
SELECT @max_p := MAX(price), @min_p := MIN(price) FROM products;
Best Practice Recommendation
- Use
SETfor scalar assignments, initializing variables, or when you expect exactly zero or one row and want strict error handling. - Use
SELECTfor performance-critical sections where you are reading multiple aggregates from the same table in a single pass, provided you are certain the query returns exactly one row.
Advanced Initialization Techniques
Inline Declaration and Initialization (T-SQL / PostgreSQL / Oracle)
Modern SQL Server versions (2008+) and other engines allow declaring and setting in one line. This reduces verbosity and ensures the variable is never in an uninitialized state.
-- T-SQL
DECLARE @StartDate DATE = GETDATE(), @Status BIT = 1;
-- PostgreSQL (PL/pgSQL)
DECLARE v_start_date DATE := CURRENT_DATE;
-- Oracle
DECLARE v_status BOOLEAN := TRUE;
Compound Assignment Operators (T-SQL Specific)
SQL Server supports compound operators (+=, -=, *=, /=, %=) which combine assignment and arithmetic. This is cleaner for counters and accumulators It's one of those things that adds up..
DECLARE @Counter INT = 0;
SET @Counter += 1; -- Equivalent to SET @Counter = @Counter + 1
Using DEFAULT (MySQL / PostgreSQL)
In MySQL stored routines and PostgreSQL, the DEFAULT keyword (or := in Postgres) provides a clean way to set initial values during declaration.
-- MySQL
DECLARE v_threshold INT DEFAULT 100;
-- PostgreSQL
DECLARE v_threshold INT DEFAULT 100;
Practical Use Cases and Patterns
1. Parameterizing Dynamic SQL
Variables are essential for building safe dynamic SQL, preventing injection attacks by using sp_executesql (SQL Server) or PREPARE/EXECUTE (MySQL/Postgres) with parameters.
-- T-SQL Safe Dynamic SQL
DECLARE @TableName NVARCHAR(128) = N'dbo.Users';
DECLARE @SQL NVARCHAR(MAX);
DECLARE @ParamDef NVARCHAR(
DECLARE @ParamDef NVARCHAR(500);
SET @SQL = N'SELECT * FROM ' + QUOTENAME(@TableName) + N' WHERE CreatedDate >= @StartDate';
SET @ParamDef = N'@StartDate DATE';
EXEC sp_executesql @SQL, @ParamDef, @StartDate = '2024-01-01';
Notice that the table name is concatenated (and sanitized via QUOTENAME), while the value is passed as a parameter. This hybrid approach is the industry-standard defense against SQL injection Practical, not theoretical..
2. Accumulators and Running Totals
Variables shine when you need to maintain state across iterations, such as computing a running balance or building a comma-separated list.
-- T-SQL: Building a CSV list safely
DECLARE @Names NVARCHAR(MAX) = '';
SELECT @Names = @Names + CASE WHEN LEN(@Names) > 0 THEN ',' ELSE '' END + Name
FROM Customers
WHERE IsActive = 1
ORDER BY Name;
SELECT @Names AS ActiveCustomers;
Caution: The order of evaluation in
SELECT @var = ...is not guaranteed in all engines. In SQL Server 2022 and Azure SQL, preferSTRING_AGG()for this pattern; the variable trick is a legacy workaround.
3. Control-Flow Flags in Stored Procedures
Variables act as lightweight flags to drive IF/ELSE logic, retry loops, or transaction decisions.
-- PostgreSQL PL/pgSQL
DECLARE
v_row_count INT := 0;
v_retries INT := 0;
BEGIN
LOOP
UPDATE inventory SET qty = qty - 1 WHERE product_id = 42 AND qty > 0;
GET DIAGNOSTICS v_row_count = ROW_COUNT;
IF v_row_count > 0 THEN
COMMIT;
EXIT;
ELSIF v_retries >= 3 THEN
RAISE EXCEPTION 'Stock update failed after % retries', v_retries;
ELSE
v_retries := v_retries + 1;
PERFORM pg_sleep(0.5);
END IF;
END LOOP;
END;
4. Swapping Values Without a Temp Table
A classic pattern that works uniformly across engines:
-- Swap two variables in T-SQL
SET @A = @A + @B;
SET @B = @A - @B;
SET @A = @A - @B;
-- Or more readably:
SELECT @A = @B, @B = @A; -- T-SQL evaluates RHS before assignment
Cross-Engine Compatibility Checklist
| Concern | SQL Server | MySQL | PostgreSQL | Oracle |
|---|---|---|---|---|
| Declaration syntax | DECLARE @x INT |
DECLARE x INT (SP only) |
DECLARE x INT (PL/pgSQL) |
DECLARE x NUMBER |
| Assignment operator | SET / SELECT |
SET / := |
:= / SELECT INTO |
:= / SELECT INTO |
| Session-level vars | No (only local) | Yes (@var) |
No | No |
| Multiple-row safety | Silent last-row win | Silent last-row win | INTO raises TOO_MANY_ROWS |
INTO raises TOO_MANY_ROWS |
| Zero-row behavior | Retains old value | Retains old value | Raises NO_DATA_FOUND |
Raises NO_DATA_FOUND |
When writing portable code, default to SET for scalar values and explicit SELECT ... INTO with exception handlers for queries that might return zero or multiple rows Small thing, real impact. Nothing fancy..
Performance Considerations
SELECTwith aggregates performs a single scan and is measurably faster than multipleSETstatements when retrieving several values from the same row.SETcompiles to a simpler execution plan and is marginally cheaper for trivial assignments, though the difference is negligible outside tight loops.- Avoid assigning variables inside cursors row-by-row when a set-based
SELECT ... INTOor window function can achieve the same result in one pass. Row-by-row variable manipulation is the number-one cause of "mystery slowness" in legacy T-SQL
Conclusion: Choosing the Right Tool for the Job
The humble variable is far more than a simple placeholder; it is a fundamental building block for logic, control, and data manipulation in SQL. Practically speaking, as we've seen, its utility spans from simple value retention and row-counting to complex conditional logic and even clever arithmetic. On the flip side, its very flexibility introduces significant pitfalls, particularly around scope, engine-specific syntax, and the silent failures that can arise from using SELECT for assignment inappropriately Turns out it matters..
Bottom line: that effective variable usage is dictated by context. For lightweight flags or iterative logic within a stored procedure, local variables declared in the procedure body provide a clean and safe mechanism. For aggregating data or extracting a single value from a query, SELECT ... Still, iNTO with proper error handling for zero or multiple rows is the solid, set-based approach. The session-level variables of MySQL, while convenient, should be used with an awareness of their limitations in portability and scope No workaround needed..
The bottom line: mastering variables is about moving beyond how to assign a value to understanding when and why each method is the correct choice. By adhering to the patterns and compatibility guidelines outlined here, you can write SQL code that is not only more efficient and reliable but also more maintainable and portable across the diverse landscape of database platforms. The goal is to let variables enhance your code's logic without becoming a source of subtle bugs or performance bottlenecks.