SQL DECLARE is a procedural statement, not part of core ANSI SQL, that reserves memory for a variable, cursor, or table variable in the current session or execution block. Once declared, the identifier exists only within the scope (batch, function, stored procedure, trigger) where it was created. DECLARE is immediately followed by one or more identifiers, each paired with a data type and an optional default value or query definition.Key behaviors:- Variables hold scalar values and can be reassigned with SET or SELECT.- Cursors declared with DECLARE name CURSOR FOR query create a pointer that can later be OPENed, FETCHed, and CLOSEd.- Table variables (SQL Server only) allocate an in-memory table that behaves like a temporary table but follows variable scope and lifetime.Caveats:- DECLARE is interpreted at parse time, so variable names must be unique within the scope.- Memory use is limited by the database engine’s session limits; excessive table variables can spill to tempdb (SQL Server) or trigger out-of-memory errors.- SQLite lacks native DECLARE; PostgreSQL requires it inside a DECLARE block of PL/pgSQL functions or DO statements, not in plain SQL.
variable_name
(identifier) - Name of the variable or table variablecursor_name
(identifier) - Name of the cursor being declareddatatype
(data type) - Any valid data type supported by the dialectinitial_value / default
(expression) - Optional expression assigned on declarationselect_statement
(query) - The query a cursor will iterate overcolumn_list
(column definitions) - Columns for a table variableSET, SELECT INTO, BEGIN...END, CURSOR, CREATE TABLE, EXECUTE, WITH
Microsoft SQL Server 6.0 (1995)
A variable is visible only inside the batch, stored procedure, function, or trigger where it was declared. It vanishes automatically when execution ends.
Yes. In SQL Server you can separate them with commas:DECLARE @a INT = 1, @b NVARCHAR(50) = 'text';
Not directly. DECLARE must appear inside a PL/pgSQL block such as DO $$ ... $$ or within a stored function.
Table variables lack full optimizer statistics. For large row counts, SQL Server may choose inefficient plans. Switch to a temporary table with CREATE TABLE #temp for better performance.