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:
CREATE VIEW placed_students ASSELECT s.name, p.name AS programme, s.packageFROM students sJOIN programmes p ON s.programme_id = p.idWHERE 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:
DELIMITER //CREATE PROCEDURE give_raise(IN prog INT, IN pct DECIMAL(4,2))BEGINUPDATE studentsSET 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:
DELIMITER //CREATE FUNCTION pkg_band(pkg DECIMAL(6,2))RETURNS VARCHAR(10) DETERMINISTICBEGINRETURN 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
- 01A view is a named saved query that behaves like a table and is always current.
- 02Views hide complex joins and can restrict which columns/rows a user sees.
- 03Stored procedures take parameters and run multi-statement logic via CALL.
- 04Stored functions return one value and can be used inside queries.
- 05Keep data-heavy logic in routines; keep fast-changing business rules in application code.
