Aral Code

Advanced MySQL Lesson 10 of 13

MySQL Views, Stored Procedures, Triggers and Transactions

Save queries as views, write stored procedures with parameters, react to changes with triggers, and keep related changes safe with START TRANSACTION, COMMIT and ROLLBACK.

MySQL can store logic inside the database itself: views (saved queries), stored procedures (saved programs), and triggers (code that runs automatically). Transactions make sure related changes happen together.

Views

SQL A view of order totals
CREATE VIEW order_totals AS
SELECT o.id AS order_id, c.name AS customer, o.order_date, o.status,
       SUM(oi.qty * p.price) AS total
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
GROUP BY o.id;

SELECT * FROM order_totals WHERE status = 'utang' ORDER BY total DESC;

A view stores the query, not the data, so it's always up to date. Use views to hide complex joins and to give users access to only some columns.

Stored procedures (MySQL)

A stored procedure is a named program stored in MySQL, with parameters:

DELIMITER //

CREATE PROCEDURE record_sale(IN p_product_id INT, IN p_qty INT)
BEGIN
  DECLARE current_stock INT;

  SELECT stock INTO current_stock FROM products WHERE id = p_product_id;

  IF current_stock IS NULL THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Product not found';
  ELSEIF current_stock < p_qty THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Not enough stock';
  ELSE
    UPDATE products SET stock = stock - p_qty WHERE id = p_product_id;
  END IF;
END //

DELIMITER ;

CALL record_sale(2, 5);
  • DELIMITER // temporarily changes the statement end marker, so the semicolons inside the procedure don't end the CREATE. phpMyAdmin has a Delimiter box for this.
  • IN parameters bring values in; OUT parameters send values back.
  • SIGNAL raises an error that the calling app receives.
  • CALL runs it.

Procedures are useful when several apps share the same business rules. Many teams, though, keep logic in the app code (PHP, Java…) where it's easier to test and version.

Triggers (MySQL)

A trigger runs automatically before or after an INSERT, UPDATE or DELETE:

CREATE TABLE price_history (
  product_id INT, old_price DECIMAL(10,2), new_price DECIMAL(10,2),
  changed_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TRIGGER log_price_change
AFTER UPDATE ON products
FOR EACH ROW
  INSERT INTO price_history (product_id, old_price, new_price)
  SELECT OLD.id, OLD.price, NEW.price
  WHERE OLD.price <> NEW.price;

OLD and NEW refer to the row before and after the change. Now every price change is recorded automatically, an easy audit trail.

Transactions

A transaction groups statements so they all succeed or all fail. The classic example is transferring money:

SQL Commit and rollback
CREATE TABLE accounts (name TEXT, balance INTEGER);
INSERT INTO accounts VALUES ('Juan', 1000), ('Maria', 500);

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 300 WHERE name = 'Juan';
UPDATE accounts SET balance = balance + 300 WHERE name = 'Maria';
COMMIT;

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 5000 WHERE name = 'Juan';
ROLLBACK;   -- something was wrong: undo

SELECT * FROM accounts;

In MySQL the syntax is START TRANSACTION; … COMMIT; or ROLLBACK;. Transactions require the InnoDB engine (the default). In PHP's PDO: $pdo->beginTransaction(), $pdo->commit() and $pdo->rollBack().

ACID

LetterMeaning
AtomicityAll or nothing
ConsistencyRules (keys, constraints) always hold
IsolationSimultaneous transactions don't see each other's half-finished work
DurabilityOnce committed, changes survive a crash or power outage

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. What does a view store?
2. How do you run a stored procedure?
3. In a trigger, what do OLD and NEW mean?
4. What does ROLLBACK do?

By Sir Reyel · Last updated 2026-12-04