Search⌘ K
AI Features

User-Defined Variables

Explore how user-defined variables in MySQL can streamline your SQL code by avoiding repetitive conditions and clarifying intent. Learn syntax, data type limitations, and their session-based scope to optimize your database queries effectively.

In previous encounters with SQL, we have encountered repetitive values in a sequence of SQL statements. To illustrate this problem, let us consider a scenario where we are handed a set of car models. In terms of SQL, we are working with the following data model:

MySQL
-- Generate a temporary table for sample car models.
DROP TABLE IF EXISTS CarModel;
CREATE TEMPORARY TABLE CarModel
(
id INT auto_increment,
manufacturer TEXT DEFAULT NULL,
name TEXT DEFAULT NULL,
`power (kW)` INT DEFAULT NULL,
PRIMARY KEY (id)
);

The above-defined temporary table CarModel defines four columns, namely id, manufacturer, name, and power (kW). The first column identifies each car model through an automatically generated numeric ID. The remaining three attributes describe the car model by manufacturer, ...