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
