Up to now, every SQL statement we wrote was sent from a client (the mysql prompt, Workbench or an application) and forgotten once it ran. But some logic is needed again and again: "transfer money between two accounts", "give a department's statistics", "work out an employee's years of service". Instead of copying the same SQL into every application, we can store it inside the database under a name and call it whenever we need it.
MySQL offers two kinds of such stored routines: stored procedures and stored functions. In this chapter we will write both, learn parameters (IN, OUT, INOUT), variables, IF/CASE, loops, cursors and error handling, and finish with a safe money-transfer procedure that uses what we learned in the Transactions in SQL chapter.
Creating routines changes the database, so these examples were run in a copy of company_db on MySQL 8.4 (do the same on your machine). All outputs are real.
What Are Stored Procedures and Functions?
A stored procedure is a named block of SQL statements saved in the database and executed with
CALL. A stored function is a named block that returns a single value and can be used inside expressions, just like built-in functions such asUPPER()orROUND().
Why store logic in the database?
Reuse and consistency: the transfer rule is written once. The Android app, the website and the admin script all CALL the same procedure, so they cannot each implement it slightly differently.
Fewer network round trips: a procedure can run ten statements with one CALL, instead of the application sending ten separate statements.
Security: you can let a user
EXECUTEa procedure without giving them direct UPDATE rights on the table. They can only change data in the way the procedure allows.Encapsulation: if the table structure changes, you update the procedure, and callers keep working.
There are downsides too. Procedural SQL is harder to test, debug and version-control than application code, it ties you to one database vendor (MySQL, Oracle PL/SQL and SQL Server T-SQL all differ), and heavy logic in the database can make it a bottleneck. Many modern teams keep business logic in the application and use routines for focused, data-heavy tasks. Know both sides; interviewers like to ask.
The DELIMITER Problem
A procedure body contains several statements, each ending with ;. But the mysql client also uses ; to decide where your statement ends and sends it to the server. Without help, it would send CREATE PROCEDURE ... SELECT ...; after the first semicolon, cutting the procedure in half.
The solution is the client command DELIMITER, which temporarily changes the end-of-statement marker:
DELIMITER // -- from now on, a statement ends with //
CREATE PROCEDURE ...
BEGIN
statement1; -- these ; are now just part of the body
statement2;
END // -- the whole CREATE is sent here
DELIMITER ; -- back to normalDELIMITER is understood by the mysql command-line client (and tools like Workbench), not by the server. When you create a routine from application code through a driver, you send the whole CREATE statement as one string and do not use DELIMITER at all.
Your First Stored Procedure
DELIMITER //
CREATE PROCEDURE get_dept_employees(IN p_dept_id INT)
BEGIN
SELECT emp_id, name, salary
FROM employees
WHERE dept_id = p_dept_id
ORDER BY salary DESC;
END //
DELIMITER ;Parts of the definition:
get_dept_employeesis the procedure's name, stored in the current database.(IN p_dept_id INT)is a parameter list. Thep_prefix is a common habit to avoid confusing parameters with column names.BEGIN ... ENDwraps the body (a compound statement).
Run it with CALL:
CALL get_dept_employees(20);+--------+--------------+-----------+
| emp_id | name | salary |
+--------+--------------+-----------+
| 4 | Sneha Kapoor | 110000.00 |
| 5 | Vikram Singh | 62000.00 |
| 6 | Ananya Das | 58000.00 |
+--------+--------------+-----------+
3 rows in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)A SELECT inside a procedure sends its result set straight to the caller. The extra "Query OK" line is the status of the CALL itself. Research (dept 50) has no employees, so CALL get_dept_employees(50) prints Empty set. Calling with the wrong number of arguments is an error:
CALL get_dept_employees();ERROR 1318 (42000): Incorrect number of arguments for PROCEDURE company_db.get_dept_employees; expected 1, got 0(MySQL procedures have no default parameter values; every parameter must be passed.)
Parameters: IN, OUT and INOUT
Mode | Direction | Typical use |
|---|---|---|
| Caller → procedure. Changes inside are not visible to the caller. | Inputs such as an id or an amount |
| Procedure → caller. Starts as NULL inside the procedure. | Returning one or more computed values |
| Both ways: the caller passes a value, the procedure may change it | Updating a value in place, counters |
OUT Parameters
This procedure returns two values for a department: the head count and the average salary. SELECT ... INTO stores query results into variables instead of displaying them.
DELIMITER //
CREATE PROCEDURE dept_stats(IN p_dept_id INT,
OUT p_count INT,
OUT p_avg DECIMAL(10,2))
BEGIN
SELECT COUNT(*), AVG(salary)
INTO p_count, p_avg
FROM employees
WHERE dept_id = p_dept_id;
END //
DELIMITER ;The caller passes user variables (names starting with @) to receive the results:
CALL dept_stats(10, @cnt, @avg);
SELECT @cnt AS employees, @avg AS avg_salary;+-----------+------------+
| employees | avg_salary |
+-----------+------------+
| 3 | 113333.33 |
+-----------+------------+
1 row in set (0.00 sec)The CALL itself reported 1 warning. SHOW WARNINGS explains it:
+-------+------+--------------------------------------------+
| Level | Code | Message |
+-------+------+--------------------------------------------+
| Note | 1265 | Data truncated for column 'p_avg' at row 1 |
+-------+------+--------------------------------------------+The true average is (150000 + 95000 + 95000) / 3 = 113333.333..., and it was rounded to fit DECIMAL(10,2). Here that is fine, but always choose parameter types big enough for the values they will hold. For Research (dept 50) the same call returns 0 and NULL, because AVG of no rows is NULL.
INOUT Parameters
DELIMITER //
CREATE PROCEDURE add_gst(INOUT p_price DECIMAL(10,2), IN p_rate INT)
BEGIN
SET p_price = ROUND(p_price * (100 + p_rate) / 100, 2);
END //
DELIMITER ;
SET @price = 2500.00;
CALL add_gst(@price, 18);
SELECT @price;+---------+
| @price |
+---------+
| 2950.00 |
+---------+
1 row in set (0.00 sec)The procedure read 2,500, added 18% GST and wrote 2,950 back into the same variable.
Variables and Control Flow
Local Variables
Inside a BEGIN ... END block, declare local variables with DECLARE (they must come at the start of the block, before other statements) and assign them with SET or SELECT ... INTO:
DECLARE v_salary DECIMAL(10,2); -- starts as NULL
DECLARE i INT DEFAULT 1; -- starts as 1
SET i = i + 1;
SELECT salary INTO v_salary FROM employees WHERE emp_id = 4;Local variable | User variable |
|---|---|
No prefix: | @ prefix: |
Declared with a type, inside BEGIN ... END | Not declared; created by assignment |
Exists only while the block runs | Lives until the connection (session) ends |
SELECT ... INTO must return at most one row. If it returns no rows, the variables keep their previous values (a "No data" condition is raised, which a NOT FOUND handler can catch); if it returns more than one row, you get ERROR 1172 (42000): Result consisted of more than one row.
IF ... ELSEIF ... ELSE
DELIMITER //
CREATE PROCEDURE salary_band(IN p_emp_id INT, OUT p_band VARCHAR(20))
BEGIN
DECLARE v_salary DECIMAL(10,2);
SELECT salary INTO v_salary FROM employees WHERE emp_id = p_emp_id;
IF v_salary IS NULL THEN
SET p_band = 'Not found';
ELSEIF v_salary >= 100000 THEN
SET p_band = 'Senior';
ELSEIF v_salary >= 60000 THEN
SET p_band = 'Mid';
ELSE
SET p_band = 'Junior';
END IF;
END //
DELIMITER ;
CALL salary_band(4, @b1); CALL salary_band(9, @b2);
CALL salary_band(8, @b3); CALL salary_band(99, @b4);
SELECT @b1, @b2, @b3, @b4;+--------+------+--------+-----------+
| @b1 | @b2 | @b3 | @b4 |
+--------+------+--------+-----------+
| Senior | Mid | Junior | Not found |
+--------+------+--------+-----------+
1 row in set (0.00 sec)Sneha (110,000) is Senior, Arjun (82,000) Mid, Meera (48,000) Junior, and employee 99 does not exist, so v_salary stayed NULL. Note that the statement IF ... END IF used here is different from the IF() function you can use in a SELECT. There is also a CASE ... END CASE statement, which works like the CASE expression from the CASE Expression chapter but runs statements in each branch.
Loops
MySQL has three loop statements:
Loop | Checks condition | Shape |
|---|---|---|
| Before each iteration (may run 0 times) |
|
| After each iteration (runs at least once) |
|
| Never; you exit with |
|
Inside labelled loops, LEAVE label works like break and ITERATE label works like continue. A small WHILE example:
DELIMITER //
CREATE PROCEDURE print_multiples(IN p_n INT, IN p_upto INT)
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE result VARCHAR(255) DEFAULT '';
WHILE i <= p_upto DO
SET result = CONCAT(result, p_n * i, ' ');
SET i = i + 1;
END WHILE;
SELECT TRIM(result) AS multiples;
END //
DELIMITER ;
CALL print_multiples(7, 5);+---------------+
| multiples |
+---------------+
| 7 14 21 28 35 |
+---------------+
1 row in set (0.00 sec)SQL is a set-based language. If you catch yourself writing a loop that updates rows one by one, there is almost always a single UPDATE or INSERT ... SELECT that does the same job faster. Use loops for genuinely step-by-step logic.
Cursors: Processing a Result Row by Row
A cursor lets a routine walk through the rows of a SELECT one at a time. MySQL cursors are read-only and forward-only. The pattern always has the same five steps:
DECLAREthe cursor for a SELECT.DECLARE CONTINUE HANDLER FOR NOT FOUNDto set a "done" flag when rows run out.OPENthe cursor.FETCHin a loop until the flag is set.CLOSEthe cursor.
DELIMITER //
CREATE PROCEDURE dept_name_list(IN p_dept_id INT, OUT p_names VARCHAR(500))
BEGIN
DECLARE v_name VARCHAR(50);
DECLARE done INT DEFAULT FALSE;
DECLARE emp_cur CURSOR FOR
SELECT name FROM employees WHERE dept_id = p_dept_id ORDER BY name;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
SET p_names = '';
OPEN emp_cur;
read_loop: LOOP
FETCH emp_cur INTO v_name;
IF done THEN
LEAVE read_loop;
END IF;
SET p_names = IF(p_names = '', v_name, CONCAT(p_names, ', ', v_name));
END LOOP;
CLOSE emp_cur;
END //
DELIMITER ;
CALL dept_name_list(10, @names);
SELECT @names;+---------------------------------------+
| @names |
+---------------------------------------+
| Aarav Sharma, Priya Iyer, Rohan Mehta |
+---------------------------------------+
1 row in set (0.00 sec)Trace for department 10: FETCH returns Aarav, Priya, Rohan in turn, each appended to the list. The fourth FETCH finds no row, the NOT FOUND handler sets done = TRUE, execution continues with the IF, and LEAVE exits the loop. Without the handler, the fourth FETCH would raise an error.
The order of DECLAREs matters: variables (and conditions) first, then cursors, then handlers. Declaring a variable after a cursor fails with ERROR 1337 (42000): Variable or condition declaration after cursor or handler declaration. And honestly, this particular job is a one-liner with GROUP_CONCAT(name ORDER BY name SEPARATOR ', '). The cursor version is here to show the pattern, which you need when each row requires several statements of its own.
Error Handling: SIGNAL, Handlers and Transactions
Two tools let a routine deal with errors:
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '...'raises your own error. SQLSTATE'45000'means "unhandled user-defined exception". The caller sees error 1644 with your message.DECLARE ... HANDLER FOR conditionsays what to do when an error happens. ACONTINUEhandler runs its statement and carries on; anEXIThandler runs its statement and then leaves the BEGIN ... END block. Conditions includeSQLEXCEPTION(any error),SQLWARNING,NOT FOUND, a specific error number such as1062, orSQLSTATE 'xxxxx'.
Remember from the Transactions chapter that MySQL does not roll back a transaction just because one statement failed. An EXIT handler that calls ROLLBACK is the standard fix. Here is a complete money transfer using the accounts table from that chapter (Rahul 5,000, Kavya 3,000):
DELIMITER //
CREATE PROCEDURE transfer_money(IN p_from INT, IN p_to INT, IN p_amount DECIMAL(10,2))
BEGIN
DECLARE v_balance DECIMAL(10,2);
-- On ANY error: undo everything, then pass the error on to the caller
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
IF p_amount <= 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Amount must be positive';
END IF;
START TRANSACTION;
SELECT balance INTO v_balance
FROM accounts WHERE acc_id = p_from
FOR UPDATE; -- lock the source row
IF v_balance IS NULL THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Source account not found';
END IF;
IF v_balance < p_amount THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient balance';
END IF;
UPDATE accounts SET balance = balance - p_amount WHERE acc_id = p_from;
UPDATE accounts SET balance = balance + p_amount WHERE acc_id = p_to;
IF ROW_COUNT() = 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Destination account not found';
END IF;
COMMIT;
END //
DELIMITER ;A successful transfer:
CALL transfer_money(1, 2, 1500);
SELECT * FROM accounts;+--------+--------+---------+
| acc_id | holder | balance |
+--------+--------+---------+
| 1 | Rahul | 3500.00 |
| 2 | Kavya | 4500.00 |
+--------+--------+---------+
2 rows in set (0.00 sec)Three failing calls:
CALL transfer_money(1, 2, 9000);
CALL transfer_money(1, 99, 500);
CALL transfer_money(1, 2, -5);ERROR 1644 (45000): Insufficient balance
ERROR 1644 (45000): Destination account not found
ERROR 1644 (45000): Amount must be positiveSELECT * FROM accounts;+--------+--------+---------+
| acc_id | holder | balance |
+--------+--------+---------+
| 1 | Rahul | 3500.00 |
| 2 | Kavya | 4500.00 |
+--------+--------+---------+
2 rows in set (0.00 sec)The second call is the interesting one. By the time the procedure discovered that account 99 does not exist, it had already debited Rahul by 500. The SIGNAL triggered the EXIT handler, which rolled the debit back, and RESIGNAL re-raised the original error so the caller still learns what went wrong. The balances are exactly as before. (ROW_COUNT() returns the number of rows changed by the previous statement.)
Stored Functions
A stored function returns exactly one value with RETURN, takes only IN parameters, and is used inside expressions rather than with CALL:
CREATE FUNCTION name(param type, ...)
RETURNS return_type
[DETERMINISTIC | NOT DETERMINISTIC]
[CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA]
BEGIN
...
RETURN value;
ENDError 1418 and the DETERMINISTIC Keyword
Try a function without any characteristics:
DELIMITER //
CREATE FUNCTION bad_func(p_date DATE) RETURNS INT
BEGIN
RETURN TIMESTAMPDIFF(YEAR, p_date, '2025-01-01');
END //
DELIMITER ;ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)Since MySQL 8.0, binary logging is on by default (it is used for replication and point-in-time recovery). To keep replicas consistent, MySQL insists that you declare at least one of:
DETERMINISTIC: the same inputs always give the same result (noNOW(),RAND(), or reading tables that may change).NO SQL: the body contains no SQL statements.READS SQL DATA: the body reads tables but does not modify them.
MySQL trusts your declaration; it does not check it. Declaring a function DETERMINISTIC when it is not can produce wrong results (for example, in replication or when the optimizer reuses a value). Be honest. Setting log_bin_trust_function_creators = 1 also silences the error, but it hides the problem rather than fixing it.
Two Working Functions
A pure calculation, honestly declared DETERMINISTIC (we pass the "as of" date instead of using CURDATE(), which would make it non-deterministic):
DELIMITER //
CREATE FUNCTION years_of_service(p_hire DATE, p_as_of DATE)
RETURNS INT
DETERMINISTIC
BEGIN
RETURN TIMESTAMPDIFF(YEAR, p_hire, p_as_of);
END //
CREATE FUNCTION dept_name_of(p_dept_id INT)
RETURNS VARCHAR(50)
READS SQL DATA
BEGIN
DECLARE v_name VARCHAR(50);
SELECT dept_name INTO v_name FROM departments WHERE dept_id = p_dept_id;
RETURN COALESCE(v_name, 'No department');
END //
DELIMITER ;Now use them like built-in functions, in the SELECT list and even in WHERE:
SELECT name, hire_date,
years_of_service(hire_date, '2025-01-01') AS years,
dept_name_of(dept_id) AS department
FROM employees
WHERE years_of_service(hire_date, '2025-01-01') >= 5
ORDER BY years DESC;+--------------+------------+-------+-------------+
| name | hire_date | years | department |
+--------------+------------+-------+-------------+
| Sneha Kapoor | 2017-11-20 | 7 | Sales |
| Aarav Sharma | 2018-04-12 | 6 | Engineering |
| Priya Iyer | 2019-07-01 | 5 | Engineering |
| Karan Patel | 2019-09-23 | 5 | HR |
+--------------+------------+-------+-------------+
4 rows in set (0.00 sec)TIMESTAMPDIFF(YEAR, ...) counts only complete years: Rohan, hired 2020-01-15, has 4 complete years on 2025-01-01, so he is not listed. And dept_name_of(NULL) returns 'No department' thanks to the COALESCE.
Performance warning: a function that runs a query, like
dept_name_of, is executed once per row. On ten rows that is fine; on a million rows it is a million small queries. A JOIN todepartmentsdoes the same job in one pass. Use table-reading functions for convenience on small results, not as a replacement for joins.
Procedure vs Function
Feature | Stored procedure | Stored function |
|---|---|---|
How it is run |
| Inside an expression: |
Returns | Nothing directly; uses OUT/INOUT parameters and/or result sets | Exactly one value via |
Parameters | IN, OUT, INOUT | IN only |
Can return result sets (SELECT to client) | Yes | No |
Transactions (START TRANSACTION, COMMIT, ROLLBACK) | Allowed | Not allowed |
Typical use | Business operations: transfer, place order, monthly batch job | Reusable calculations and lookups |
Mixing them up gives clear errors:
SELECT get_dept_employees(10);
CALL years_of_service('2020-01-01', '2025-01-01');ERROR 1305 (42000): FUNCTION company_db.get_dept_employees does not exist
ERROR 1305 (42000): PROCEDURE company_db.years_of_service does not exist(Procedures and functions live in separate namespaces, which is why MySQL reports "does not exist" rather than "wrong type".)
Managing Routines
SHOW PROCEDURE STATUS WHERE Db = 'company_db'; -- list procedures
SHOW FUNCTION STATUS WHERE Db = 'company_db'; -- list functions
SHOW CREATE PROCEDURE add_gst; -- see the full definitionThe data dictionary view information_schema.ROUTINES gives the same information as a normal table you can query:
SELECT ROUTINE_NAME, ROUTINE_TYPE, IS_DETERMINISTIC, SQL_DATA_ACCESS
FROM information_schema.ROUTINES
WHERE ROUTINE_SCHEMA = DATABASE()
ORDER BY ROUTINE_TYPE, ROUTINE_NAME;+--------------------+--------------+------------------+-----------------+
| ROUTINE_NAME | ROUTINE_TYPE | IS_DETERMINISTIC | SQL_DATA_ACCESS |
+--------------------+--------------+------------------+-----------------+
| dept_name_of | FUNCTION | NO | READS SQL DATA |
| years_of_service | FUNCTION | YES | CONTAINS SQL |
| add_gst | PROCEDURE | NO | CONTAINS SQL |
| dept_name_list | PROCEDURE | NO | CONTAINS SQL |
| dept_stats | PROCEDURE | NO | CONTAINS SQL |
| get_dept_employees | PROCEDURE | NO | CONTAINS SQL |
| print_multiples | PROCEDURE | NO | CONTAINS SQL |
| salary_band | PROCEDURE | NO | CONTAINS SQL |
| transfer_money | PROCEDURE | NO | CONTAINS SQL |
+--------------------+--------------+------------------+-----------------+
9 rows in set (0.00 sec)Notice that every procedure shows CONTAINS SQL, even the ones that read tables: that is simply the default characteristic when you do not declare one. To remove a routine, use DROP:
DROP PROCEDURE IF EXISTS add_gst;
DROP FUNCTION IF EXISTS dept_name_of;Some practical facts:
There is no way to edit a routine's body in place.
ALTER PROCEDUREonly changes characteristics such as the comment or SQL SECURITY. To change the code, DROP it and CREATE it again (usually asDROP PROCEDURE IF EXISTS ...followed byCREATE PROCEDURE ...in your migration scripts).By default a routine runs with the privileges of its definer (
SQL SECURITY DEFINER), the user who created it. That is what makes the "grant EXECUTE but not UPDATE" security model work.SQL SECURITY INVOKERruns it with the caller's privileges instead.Routines belong to a database; dropping the database drops its routines.
Common Mistakes
Forgetting DELIMITER in the mysql client, so the CREATE is cut off at the first semicolon and you get a confusing syntax error.
Parameter named like a column. Inside a routine, when a parameter or local variable has the same name as a column, MySQL treats the name as the variable. We tested a procedure with parameter
salaryrunningSELECT COUNT(*) FROM employees WHERE salary = salary:CALL count_by_salary(95000)returned 10, not 2, because the condition became "parameter = parameter", which is true for every row. Use prefixes likep_andv_.Missing NOT FOUND handler in a cursor loop, causing an error after the last row, or an infinite loop if the done flag is never checked.
Errors inside a transaction without a handler, leaving partial changes in an open transaction.
Lying about DETERMINISTIC just to get past error 1418.
Row-by-row loops where one set-based statement would do.
Calling query-running functions on large tables in SELECT or WHERE, instead of a JOIN.
Interview Questions
What is a stored procedure?
A named set of SQL statements stored in the database and executed with CALL. It can take IN, OUT and INOUT parameters, contain control flow, and return result sets.
What is the difference between a stored procedure and a function?
A function returns exactly one value and is used inside expressions (SELECT, WHERE); it takes only IN parameters and cannot manage transactions. A procedure is called with CALL, can return values through OUT parameters and result sets, and can run transactions.
What are IN, OUT and INOUT parameters?
IN passes a value into the procedure; OUT passes a value back to the caller (starting as NULL inside); INOUT passes a value in and lets the procedure change it.
Why do we use DELIMITER?
The mysql client ends a statement at each semicolon. Changing the delimiter lets the semicolons inside the routine body reach the server as part of one CREATE statement.
What is a cursor?
A mechanism for processing a query result one row at a time inside a routine: DECLARE, OPEN, FETCH in a loop (with a NOT FOUND handler to detect the end), CLOSE. MySQL cursors are read-only and forward-only.
How do you handle errors in a MySQL stored procedure?
Declare a handler (DECLARE EXIT|CONTINUE HANDLER FOR SQLEXCEPTION ...) to react to errors, typically ROLLBACK and RESIGNAL; raise custom errors with SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '...'.
What does error 1418 mean when creating a function?
Binary logging is enabled and the function is not declared DETERMINISTIC, NO SQL or READS SQL DATA. Add the correct characteristic.
What are the advantages and disadvantages of stored procedures?
Advantages: reuse, consistency, fewer round trips, security through EXECUTE privileges. Disadvantages: harder testing and version control, vendor lock-in, and extra load on the database server.
Summary
Stored routines keep reusable SQL logic inside the database. Procedures are run with
CALL; functions return one value and are used in expressions.Use
DELIMITERin the mysql client to write multi-statement bodies.Parameters are IN (default), OUT or INOUT; functions accept only IN.
DECLARElocal variables at the top of a block; assign withSETorSELECT ... INTO.Control flow: IF/ELSEIF/ELSE, CASE, and WHILE, REPEAT and LOOP with LEAVE/ITERATE.
Cursors process rows one by one, with a NOT FOUND handler to end the loop.
SIGNALraises custom errors; an EXIT handler with ROLLBACK and RESIGNAL makes a transaction all-or-nothing.Functions must be declared DETERMINISTIC, NO SQL or READS SQL DATA when binary logging is on (the MySQL 8 default), and that declaration must be truthful.
Next, in Triggers, we will write routines that the database runs automatically whenever rows are inserted, updated or deleted.