liveBook · Manning

SET statement

As explained in Learn SQL in a Month of Lunches

A SET statement is an SQL statement that assigns a value to a variable or configures a database or session setting.

SET assigns a value. Think of it like filling in a labeled spreadsheet cell: name the variable, use =, then provide the value. In MySQL, a user-defined variable such as @TitleName can hold a string, number, or NULL; its type follows the assigned value. section 13.1.1 section 13.4.2

Save a title to reuse

SET @TitleName = 'The Sum Also Rises'; SELECT @TitleName; The first line stores the title, and the second checks it. SET accepts = or := for assignment, although := is required in some variable-assignment contexts. section 13.1.1

SET can also assign a value found by a query. For example, save the earliest 2021 order date, then use that variable to retrieve the titles, quantities, and prices from that order. Because SET does not display its assigned value automatically, follow it with SELECT when checking a query. section 13.3.4

SET @FirstOrderDate = (
    SELECT MIN(OrderDate)
    FROM orderheader
    WHERE OrderDate BETWEEN '2021-01-01' AND '2021-12-31');
 
SELECT @FirstOrderDate AS FirstOrderDate;

This two-step query stores an order date returned by a subquery, then displays the saved value for verification. section 13.3.4

SET also appears in UPDATE statements, where it names the column value to change. A joined update can set title prices for rows related to a chosen author. Join syntax for UPDATE differs among MySQL, PostgreSQL, and SQL Server, so use the form supported by your database. section 17.1.4

Assign inside a stored procedure

DECLARE _TitleID int; SET _TitleID = 101; Inside a MySQL stored procedure, declare a local variable and its data type before assigning it. SET may assign a fixed value or the result of a subquery; DEFAULT is another option at declaration time. section 22.1.1

How Learn SQL in a Month of Lunches covers it

How deep it goes
Demonstrates literal, NULL, and subquery assignments, verification, stored-procedure use, and joined updates without detailing database settings.
Examples
Uses a saved title, the first 2021 order date, an author-related price update, and a TitleID procedure variable.
What it assumes
Introduces variable naming and assignment from zero while relying on SELECT, WHERE, joins, and UPDATE for larger queries.
What you can do after
Apply it via MySQL to assign and check variables or set values during updates.
How it connects
Connects variables with SELECT, subqueries, UPDATE, JOIN, stored procedures, DECLARE, DEFAULT, and NULL.

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.