Sending individual SQL queries across network connections introduces network latency and risks business logic discrepancies between different client applications. A Stored Procedure is a prepared batch of SQL code compiled, optimized, and saved directly inside the database catalog. Applications execute the procedure with a single call, passing parameters and receiving outputs.
| Feature | Stored Procedure | User-Defined Function (UDF) |
|---|---|---|
| Invocation | Executed via CALL proc_name() |
Called inside expressions: SELECT func() |
| Return Value | Does not require return; uses OUT params |
Must return exactly one value or table |
| Transactions | Can manage COMMIT and ROLLBACK |
Cannot manage transactions |
DELIMITER //
CREATE PROCEDURE EnrollStudent(
IN p_first_name VARCHAR(50),
IN p_last_name VARCHAR(50),
IN p_email VARCHAR(100),
IN p_course VARCHAR(30),
OUT p_student_id INT
)
BEGIN
-- Insert the new student
INSERT INTO students (first_name, last_name, email, course, enrollment_date, gpa)
VALUES (p_first_name, p_last_name, p_email, p_course, CURRENT_DATE, 0.00);
-- Capture generated auto-increment id into OUT parameter
SET p_student_id = LAST_INSERT_ID();
END //
DELIMITER ;
-- Call procedure and retrieve OUT parameter
CALL EnrollStudent('Kavita', 'Rao', 'kavita@test.com', 'BCA', @new_id);
-- Inspect generated student ID
SELECT @new_id AS generated_student_id;
Next, let us learn how to automate events and audit trails using SQL Triggers!
A Function must always return a single value and can be called directly inside SELECT queries (e.g., SELECT my_func(col) FROM table). A Stored Procedure cannot be called directly inside a SELECT query; it is executed using CALL procedure_name() and can return zero, one, or multiple result sets.
The standard SQL delimiter is a semicolon (;). Because a stored procedure contains multiple internal semicolons inside its body, you must temporarily change the delimiter (e.g., to // or $$) so the client knows not to terminate the procedure definition prematurely.
Stored procedures are compiled and optimized once upon creation, and their execution plans are cached in database memory. They also eliminate network round-trips by executing entire multi-step business transactions directly on the database server.
Proceed to the next class in sequence to build production mastery of relational database architecture.
Continue to Class 48: SQL Triggers → Previous: ← Transactions & ACID | Full Syllabus
Explicit application procedure calls vs automatic event hooks.
Row-by-row procedural iteration within procedure routines.
Granting EXECUTE privileges without granting raw table access.
START TRANSACTION, COMMIT, and SQLEXCEPTION handlers.