Skip to main content
Albero Academy

Views & Stored Routines

Save queries as reusable views, and push logic into the database with stored procedures and functions.

Chapter 8MySQL15 min readBeginner friendly
  • #MySQL
  • #Views
  • #Stored Procedures

Once a query is useful and reused, you can name it and store it in the database. A view is a saved query that acts like a table; stored procedures and functions package multi-step logic the server runs for you.

Views — a saved query as a table

A view has no data of its own; it re-runs its query each time you select from it, so it's always current:

creating a view
CREATE VIEW placed_students AS
SELECT s.name, p.name AS programme, s.package
FROM students s
JOIN programmes p ON s.programme_id = p.id
WHERE s.status = 'placed';
SELECT * FROM placed_students WHERE package > 8; -- query it like a table

Stored procedures

A stored procedure is a named block of SQL that can take parameters and run several statements. Change the delimiter so the body's semicolons aren't misread:

a procedure with a parameter
DELIMITER //
CREATE PROCEDURE give_raise(IN prog INT, IN pct DECIMAL(4,2))
BEGIN
UPDATE students
SET package = package * (1 + pct/100)
WHERE programme_id = prog;
END //
DELIMITER ;
CALL give_raise(3, 10); -- 10% raise for programme 3

Stored functions

A function returns a single value and can be used inside a query, like the built-ins:

a reusable function
DELIMITER //
CREATE FUNCTION pkg_band(pkg DECIMAL(6,2))
RETURNS VARCHAR(10) DETERMINISTIC
BEGIN
RETURN CASE WHEN pkg >= 10 THEN 'High'
WHEN pkg >= 6 THEN 'Mid'
ELSE 'Entry' END;
END //
DELIMITER ;
SELECT name, pkg_band(package) AS band FROM students;

When to use them

Stored routines keep logic close to the data and let many apps share it — but they're harder to version-control and test than application code. Use them for data-heavy operations and integrity rules; keep business logic that changes often in the application layer.

Practice

Create a placed_students view and query it. Write a give_raise(prog, pct) procedure and call it. Write a pkg_band() function and use it in a SELECT. Note which felt right in the database versus in application code.

Key takeaways

  1. 01A view is a named saved query that behaves like a table and is always current.
  2. 02Views hide complex joins and can restrict which columns/rows a user sees.
  3. 03Stored procedures take parameters and run multi-statement logic via CALL.
  4. 04Stored functions return one value and can be used inside queries.
  5. 05Keep data-heavy logic in routines; keep fast-changing business rules in application code.