New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› MySQL› Views and Stored Procedures

Views and Stored Procedures

💻 MySQL

Save reusable queries as views and wrap multi-step work in stored procedures.

Lesson 7 of 9 Tutorial
0 of 9 completed

Views and procedures keep complex SQL on the database where every application can reuse it.

By the end of this lesson you can:
  • 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.

Warning A view runs with the permissions of its definer by default. Check who can read sensitive columns through it.

Practice

  1. Create a view of published courses.
  2. Write a procedure that accepts a student id and marks them inactive.
  3. 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

Exercise 1. A reusable view Medium
Create a view called course_catalogue that returns id, title and price for active courses, ordered by title. Then select from it.
MySQL exercise-1.txt
Expected Output
A view that always returns only active courses.

Lesson Nav

Lesson sections