Views and Stored Procedures
💻 MySQLSave reusable queries as views and wrap multi-step work in stored procedures.
Views and procedures keep complex SQL on the database where every application can reuse it.
- Create and query a view.
- Create a stored procedure.
- Know when a view is the wrong tool.
Views
A view is a saved SELECT. It behaves like a table for reading and hides complexity from the application.
CREATE VIEW active_students AS
SELECT id, name, level, email
FROM students
WHERE is_active = 1;
SELECT * FROM active_students WHERE level = 'SS2';Stored Procedures
A procedure groups statements and can accept parameters. Use them for repetitive maintenance tasks, not for every query.
DELIMITER //
CREATE PROCEDURE promote_students(IN target_level VARCHAR(20))
BEGIN
UPDATE students
SET level = target_level
WHERE is_active = 1
AND level = 'SS1';
END //
DELIMITER ;
CALL promote_students('SS2');Trade-offs
Views are simple and safe to read. Procedures can be harder to version and test. Keep business logic in application code when the team is small.
Practice
- Create a view of published courses.
- Write a procedure that accepts a student id and marks them inactive.
- Explain one downside of putting business logic in procedures.
Hands-on exercise
Create a view called course_catalogue that returns id, title and price for active courses, ordered by title. Then select from it.
Recap
Views save reusable reads and hide complexity. Procedures group writes but add maintenance cost.
Example
CREATE VIEW active_students AS
SELECT id, name, level, email
FROM students
WHERE is_active = 1;
SELECT * FROM active_students WHERE level = 'SS2';
Exercises
Expected Output
A view that always returns only active courses.
Lesson Nav
MySQL Course
0/9 lessons completed
- 1 Connecting to MySQL Tutorial
- 2 Creating Databases and Tables Tutorial
- 3 Data Types and Constraints Tutorial
- 4 Reading and Writing Data Tutorial
- 5 Joins and Relationships in MySQL Tutorial
- 6 Functions, Dates and Text Tutorial
- 7 Views and Stored Procedures Tutorial
- 8 Users, Permissions and Backups Tutorial
- 9 Project: A Small School Database Project