MySQL Stored Functions and Triggers: Audit Logs and Validation

MySQL 65 min min read Updated: Nov 27, 2026 Intermediate
MySQL Stored Functions and Triggers: Audit Logs and Validation
Intermediate Topic 2 of 3

Functions vs Procedures

FunctionProcedure
Called withInside a query: SELECT f(x)CALL p()
ReturnsExactly one valueNothing, or OUT values and result sets
Use forCalculations and formattingTasks with several steps

A Stored Function

sql CREATE FUNCTION price_with_tax(p DECIMAL(10,2), rate DECIMAL(4,2)) RETURNS DECIMAL(10,2) DETERMINISTIC BEGIN RETURN ROUND(p * (1 + rate / 100), 2); END; SELECT name, price, price_with_tax(price, 18) AS gross FROM products WHERE id <= 3 ORDER BY id;

Result:

namepricegross
Laptop899.001060.82
Phone599.00706.82
Headphones79.0093.22
DETERMINISTIC and friends Declare DETERMINISTIC when the same input always gives the same output, READS SQL DATA when it only reads tables, MODIFIES SQL DATA when it writes. If binary logging is on, MySQL refuses a function that has none of these hints (error 1418), unless an administrator sets log_bin_trust_function_creators.
sql CREATE FUNCTION customer_order_count(cid INT) RETURNS INT READS SQL DATA BEGIN DECLARE n INT; SELECT COUNT(*) INTO n FROM orders WHERE customer_id = cid; RETURN n; END; SELECT name, customer_order_count(id) AS orders FROM customers ORDER BY id;

Result:

nameorders
Asha Rao3
Ben Carter3
Chen Wei2
Dina Cohen0
Eli Brown1
Fatima Khan1
Functions in queries can be slow A function that runs a query is called once per row. On a big table that is thousands of hidden queries. Prefer a join where possible.

What Is a Trigger?

A trigger is code that MySQL runs automatically before or after INSERT, UPDATE or DELETE on a table. Inside it, NEW is the incoming row and OLD is the previous row.

BEFORE Trigger: Validate and Fix Data

sql CREATE TABLE accounts (id INT PRIMARY KEY, owner VARCHAR(30), balance DECIMAL(10,2) NOT NULL); CREATE TRIGGER trg_accounts_bi BEFORE INSERT ON accounts FOR EACH ROW BEGIN IF NEW.balance < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Opening balance cannot be negative'; END IF; SET NEW.owner = TRIM(NEW.owner); END; INSERT INTO accounts VALUES (1, ' Asha ', 100.00); SELECT id, CONCAT('[', owner, ']') AS owner, balance FROM accounts;

Result:

idownerbalance
1[Asha]100.00
sql CREATE TABLE accounts (id INT PRIMARY KEY, owner VARCHAR(30), balance DECIMAL(10,2) NOT NULL); CREATE TRIGGER trg_accounts_bi BEFORE INSERT ON accounts FOR EACH ROW BEGIN IF NEW.balance < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Opening balance cannot be negative'; END IF; END; INSERT INTO accounts VALUES (2, 'Ben', -5.00);
Error

ERROR 1644: Opening balance cannot be negative

SIGNAL raises your own error, which stops the statement. A BEFORE trigger can also change NEW values.

AFTER Trigger: Audit Log

sql CREATE TABLE accounts (id INT PRIMARY KEY, owner VARCHAR(30), balance DECIMAL(10,2) NOT NULL); CREATE TABLE account_audit (id INT AUTO_INCREMENT PRIMARY KEY, account_id INT, old_balance DECIMAL(10,2), new_balance DECIMAL(10,2), action VARCHAR(10)); CREATE TRIGGER trg_accounts_au AFTER UPDATE ON accounts FOR EACH ROW BEGIN IF OLD.balance <> NEW.balance THEN INSERT INTO account_audit (account_id, old_balance, new_balance, action) VALUES (OLD.id, OLD.balance, NEW.balance, 'UPDATE'); END IF; END; CREATE TRIGGER trg_accounts_ad AFTER DELETE ON accounts FOR EACH ROW BEGIN INSERT INTO account_audit (account_id, old_balance, new_balance, action) VALUES (OLD.id, OLD.balance, NULL, 'DELETE'); END; INSERT INTO accounts VALUES (1, 'Asha', 100), (2, 'Ben', 50); UPDATE accounts SET balance = balance - 30 WHERE id = 1; UPDATE accounts SET owner = 'Ben C.' WHERE id = 2; DELETE FROM accounts WHERE id = 2; SELECT account_id, old_balance, new_balance, action FROM account_audit ORDER BY id;

Result:

account_idold_balancenew_balanceaction
1100.0070.00UPDATE
250.00NULLDELETE

The rename of Ben did not create a row, because the balance did not change. The delete was logged with the old balance.

Keeping a Summary Column Updated

sql CREATE TABLE posts (id INT PRIMARY KEY, title VARCHAR(30), comment_count INT NOT NULL DEFAULT 0); CREATE TABLE comments (id INT AUTO_INCREMENT PRIMARY KEY, post_id INT, body VARCHAR(30)); CREATE TRIGGER trg_comments_ai AFTER INSERT ON comments FOR EACH ROW UPDATE posts SET comment_count = comment_count + 1 WHERE id = NEW.post_id; INSERT INTO posts (id, title) VALUES (1, 'Hello'); INSERT INTO comments (post_id, body) VALUES (1, 'nice'), (1, 'thanks'); SELECT id, title, comment_count FROM posts;

Result:

idtitlecomment_count
1Hello2

Listing and Dropping Triggers

sql CREATE TABLE t (id INT); CREATE TRIGGER trg_t_bi BEFORE INSERT ON t FOR EACH ROW SET NEW.id = NEW.id + 1; SELECT TRIGGER_NAME, EVENT_MANIPULATION, ACTION_TIMING FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = DATABASE();

Result:

TRIGGER_NAMEEVENT_MANIPULATIONACTION_TIMING
trg_t_biINSERTBEFORE
sql DROP TRIGGER IF EXISTS trg_t_bi;

Trigger Rules and Limits

  • MySQL supports row-level triggers only (FOR EACH ROW), no statement-level triggers.
  • You can have several triggers for the same event; FOLLOWS and PRECEDES set the order.
  • A trigger cannot modify the same table that fired it (error 1442), and cannot use COMMIT or ROLLBACK.
  • Triggers do not fire for cascading foreign key actions.
  • A failing trigger makes the whole statement fail and roll back.

Common Beginner Mistakes

MistakeWhat happensFix
Hidden business rules in triggersSurprises for developersDocument them, keep them few
Slow work in a triggerEvery insert is slowKeep triggers light
Updating the same table in a triggerError 1442Use a BEFORE trigger and SET NEW.col
Function without DETERMINISTIC or READS SQL DATAError 1418 when binlog is onAdd the right characteristic
Bulk loads firing triggersSlow importsPlan for it, or load differently

Practice

  1. Write a function full_price(price, discount_pct).
  2. Create a trigger that blocks negative stock on products.
  3. Create an audit table filled by an AFTER UPDATE trigger on products price changes.
  4. List all triggers of your schema.

Conclusion

Functions return one value and are used inside queries. Triggers run automatically on row changes, with NEW and OLD, and are great for validation and audit logs when used sparingly.

Quick Summary: CREATE FUNCTION, DETERMINISTIC, triggers, NEW, OLD, SIGNAL, audit table.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators