MySQL Stored Functions
Use a scalar routine only when its rules and execution cost are appropriate for repeated calls.
How it works
A stored function returns one value and can be used in expressions. This example converts a validated-looking cost and quantity into an exact amount using a declared DECIMAL result. Its deterministic and NO SQL declarations describe the implementation’s contract; they are not magic proof that arbitrary code is safe. For a simple multiplication an ordinary expression or generated column may be clearer, so the routine is a learning example rather than a universal design recommendation.
Run in a disposable MySQL lab
Use Oracle MySQL 8.4 with InnoDB, not Bhylu’s SQLite playground. The examples were reviewed on MySQL 8.4.8. XAMPP may provide MariaDB, which has different feature and collation behaviour. Check your actual server before running the script. These lessons do not require a change to Bhylu’s PHP, Apache or normal database service.
- On a separate lab instance, create the empty bhylu_mysql_lab schema. Stop if it already exists; do not overwrite an existing database.
- Select that schema and import the complete repair-parts seed once. It sets the documented session mode, utf8mb4 collation, UTC and English date-name locale.
- Run this lesson in a fresh copy of the seed, not after another lesson’s writes. Use the command-line client or a compatible editor. DELIMITER lines are client instructions for stored-program examples.
Download this complete lesson script. Its setup is the linked seed; review the dataset before changing it. Administrative and destructive examples are restricted to the specifically named disposable objects. Every script repeats the session settings because each new connection has its own session. No MySQL browser runner is currently available.
Example
SET NAMES utf8mb4 COLLATE utf8mb4_0900_ai_ci;
SET SESSION sql_mode = 'STRICT_TRANS_TABLES,ONLY_FULL_GROUP_BY,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
SET SESSION time_zone = '+00:00';
SET SESSION lc_time_names = 'en_US';
CREATE FUNCTION line_cost(cost DECIMAL(8,2), pieces INT)
RETURNS DECIMAL(12,2) DETERMINISTIC NO SQL
RETURN cost * pieces;
SELECT line_cost(2.50,3) AS amount;
Expected result
7.5
The result is 7.50. A real domain routine should define accepted ranges, NULL handling and errors rather than infer them from parameter names. Functions called for many rows can add execution overhead and complicate optimizer reasoning. Review binary logging, routine privileges and deployment rules on the actual server; this private lab does not establish a replication-safe production architecture.
Use the official MySQL 8.4 reference for statement contracts and version details.