Functions vs Procedures
| Function | Procedure |
| Called with | Inside a query: SELECT f(x) | CALL p() |
| Returns | Exactly one value | Nothing, or OUT values and result sets |
| Use for | Calculations and formatting | Tasks 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:
| name | price | gross |
| Laptop | 899.00 | 1060.82 |
| Phone | 599.00 | 706.82 |
| Headphones | 79.00 | 93.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:
| name | orders |
| Asha Rao | 3 |
| Ben Carter | 3 |
| Chen Wei | 2 |
| Dina Cohen | 0 |
| Eli Brown | 1 |
| Fatima Khan | 1 |
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:
| id | owner | balance |
| 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_id | old_balance | new_balance | action |
| 1 | 100.00 | 70.00 | UPDATE |
| 2 | 50.00 | NULL | DELETE |
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:
| id | title | comment_count |
| 1 | Hello | 2 |
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_NAME | EVENT_MANIPULATION | ACTION_TIMING |
| trg_t_bi | INSERT | BEFORE |
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
| Mistake | What happens | Fix |
| Hidden business rules in triggers | Surprises for developers | Document them, keep them few |
| Slow work in a trigger | Every insert is slow | Keep triggers light |
| Updating the same table in a trigger | Error 1442 | Use a BEFORE trigger and SET NEW.col |
Function without DETERMINISTIC or READS SQL DATA | Error 1418 when binlog is on | Add the right characteristic |
| Bulk loads firing triggers | Slow imports | Plan for it, or load differently |
Practice
- Write a function
full_price(price, discount_pct).
- Create a trigger that blocks negative stock on products.
- Create an audit table filled by an
AFTER UPDATE trigger on products price changes.
- 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.