Views, Stored Procedures & Triggers
Save queries as reusable views, bundle logic into stored procedures, and automate actions with triggers.
A View is a saved query. A Stored Procedure is reusable logic. A Trigger fires automatically when something happens to a table.
EXERCISE
1Views — Saved Queries You Can Use Like Tables
A view is a named, saved SELECT query stored in the database. Query it like a table, get the latest data every time, and hide complexity from other users.
Creating a view:
-- A complex join query that is run frequently:
CREATE VIEW employee_details AS
SELECT
e.id,
e.name,
e.salary,
d.name AS department,
d.location
FROM employees e
JOIN departments d ON e.department_id = d.id;
-- Now anyone can query it simply:
SELECT * FROM employee_details WHERE department = 'IT';
SELECT name, salary FROM employee_details WHERE location = 'Bangalore';
Views always show fresh data:
A view is not a snapshot — it runs the underlying query each time it is accessed. The data is always current.
Simplifying complex queries for analysts:
CREATE VIEW monthly_revenue AS
SELECT
YEAR(created_at) AS yr,
MONTH(created_at) AS mo,
COUNT(*) AS order_count,
SUM(total) AS revenue
FROM orders
WHERE status = 'completed'
GROUP BY YEAR(created_at), MONTH(created_at);
-- Analyst writes just:
SELECT * FROM monthly_revenue WHERE yr = 2024 ORDER BY mo;
Security — expose only certain columns:
-- Hide salary from junior analysts:
CREATE VIEW employees_public AS
SELECT id, name, department_id, hire_date
FROM employees;
-- DO NOT include salary in this view
-- Grant access to the view, not the underlying table
Modifying and dropping views:
CREATE OR REPLACE VIEW employee_details AS ...; -- update view definition
DROP VIEW employee_details; -- remove the view
SHOW FULL TABLES WHERE Table_type = 'VIEW'; -- list all views
Pro Tip: Views are the SQL equivalent of functions in programming — they encapsulate complexity, enable reuse, and can restrict access. Use them aggressively to keep application queries clean and simple.
EXERCISE
2Stored Procedures — Reusable Logic Inside the Database
A stored procedure is a named block of SQL that can accept parameters, contain logic, and be called repeatedly — like a function in programming, but living inside the database.
Creating a basic stored procedure:
DELIMITER //
CREATE PROCEDURE GetEmployeesByDept(IN dept_name VARCHAR(50))
BEGIN
SELECT e.name, e.salary
FROM employees e
JOIN departments d ON e.department_id = d.id
WHERE d.name = dept_name
ORDER BY e.salary DESC;
END//
DELIMITER ;
-- Call it:
CALL GetEmployeesByDept('IT');
CALL GetEmployeesByDept('HR');
Procedure with OUT parameter:
DELIMITER //
CREATE PROCEDURE GetDeptStats(
IN dept_name VARCHAR(50),
OUT total_staff INT,
OUT avg_salary DECIMAL(10,2)
)
BEGIN
SELECT COUNT(*), AVG(e.salary)
INTO total_staff, avg_salary
FROM employees e
JOIN departments d ON e.department_id = d.id
WHERE d.name = dept_name;
END//
DELIMITER ;
-- Call and capture output:
CALL GetDeptStats('IT', @staff, @avg);
SELECT @staff AS headcount, @avg AS avg_salary;
Procedure with conditional logic:
DELIMITER //
CREATE PROCEDURE GiveRaise(IN emp_id INT, IN raise_pct DECIMAL(5,2))
BEGIN
IF raise_pct > 50 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Raise cannot exceed 50%';
ELSE
UPDATE employees SET salary = salary * (1 + raise_pct / 100)
WHERE id = emp_id;
SELECT CONCAT('Raise applied: ', raise_pct, '%') AS result;
END IF;
END//
DELIMITER ;
Pro Tip: Stored procedures reduce network round-trips (one CALL instead of many queries), centralise business logic in the database, and can be granted permissions independently of the tables they access.
EXERCISE
3Triggers — Automatic Actions When Data Changes
A trigger fires automatically when a row is inserted, updated, or deleted — perfect for audit logs, data validation, and keeping derived values in sync.
Trigger syntax:
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- trigger body
-- NEW.column = the new value (INSERT/UPDATE)
-- OLD.column = the old value (UPDATE/DELETE)
END;
Audit log — record every salary change:
CREATE TABLE salary_audit (
id INT AUTO_INCREMENT PRIMARY KEY,
employee_id INT,
old_salary DECIMAL(10,2),
new_salary DECIMAL(10,2),
changed_at DATETIME DEFAULT NOW(),
changed_by VARCHAR(100) DEFAULT USER()
);
DELIMITER //
CREATE TRIGGER after_salary_update
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
IF OLD.salary != NEW.salary THEN
INSERT INTO salary_audit (employee_id, old_salary, new_salary)
VALUES (OLD.id, OLD.salary, NEW.salary);
END IF;
END//
DELIMITER ;
-- Now every salary change is automatically logged:
UPDATE employees SET salary = 85000 WHERE id = 1;
SELECT * FROM salary_audit;
BEFORE trigger — validate data before it is saved:
DELIMITER //
CREATE TRIGGER before_salary_insert
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF NEW.salary < 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Salary cannot be negative';
END IF;
IF NEW.salary > 1000000 THEN
SET NEW.salary = 1000000; -- cap at 1 million
END IF;
END//
DELIMITER ;
Pro Tip: Triggers are powerful but invisible — they fire silently whenever data changes, which can make debugging confusing. Document every trigger clearly. Use them for cross-cutting concerns like audit logs that should apply to ALL data changes.
