liveBook · Manning

DECLARE

As explained in Learn SQL in a Month of Lunches

DECLARE is an SQL keyword used to declare a variable or other procedural object and, where required, specify its data type.

DECLARE creates a variable or procedural object. For a stored procedure, it can name the variable and specify its data type, giving later SQL a value to set, check, or reuse. section 22.1.1

Declare a title ID

Inside a stored procedure, declare an integer variable and give it a starting value: DECLARE _TitleID int DEFAULT 101; You can instead assign a value later with SET, including a value returned by a subquery. DECLARE therefore defines the variable, while SET supplies or changes its value. section 22.1.1

DECLARE also creates a cursor. Its declaration contains the SELECT query that defines the rows the cursor will use. The cursor must then be OPENed, FETCHed one row at a time, and CLOSEd in that order. section 22.2.1

Keep these practical distinctions in mind:

  • MySQL can use another variable-declaration method outside stored procedures, but inside a stored procedure it uses DECLARE with a data type. section 22.1.1 section 13.1.1
  • Use SELECT to inspect a variable’s current value while checking a script or troubleshooting an unexpected result. section 13.1.1
  • Reusable variables let one query select different titles by changing one value, such as The Sum Also Rises or Pride and Predicates. section 13.1.3
DECLARE _TitleID int DEFAULT 101;

A compact example of declaring an integer variable with a default value. section 22.1.1

How Learn SQL in a Month of Lunches covers it

How deep it goes
Explains variable declarations, assignments, inspection, and cursor order, but does not detail complete procedure syntax.
Examples
Demonstrates typed TitleID declarations, DEFAULT initialization, subquery assignment, cursor definitions, and reusable TitleName filters.
What you can do after
Apply it via SQL to declare procedure variables, initialize or inspect them, and define cursor result sets.
How it connects
Connects DECLARE with variables, data types, stored procedures, cursors, SELECT, SET, OPEN, FETCH, and CLOSE.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn SQL in a Month of Lunches. The section links point to the parts of the book it draws on.