A stored procedure is a named block of SQL code saved inside the database and run with one call. Procedures bundle several steps – checks, inserts, updates – into a single, reusable, secure operation.
What You Will Learn
- Create and call a stored procedure in MySQL
- IN and OUT parameters
- Transactions inside a procedure
- Functions vs procedures
- PostgreSQL syntax and when to use procedures
Prerequisites
SQL Basics and MySQL.
A Simple Procedure (MySQL)
DELIMITER //
CREATE PROCEDURE get_students_by_city(IN p_city VARCHAR(50))
BEGIN
SELECT id, name, age FROM students WHERE city = p_city ORDER BY name;
END //
DELIMITER ;
CALL get_students_by_city('Ludhiana');
id | name | age 1 | Aman | 21 3 | Karan | 25
Explanation: DELIMITER // temporarily changes the statement terminator so the semicolons inside the body do not end the CREATE statement. IN p_city is an input parameter. The output uses the sample data from SQL Basics.
OUT Parameters
DELIMITER //
CREATE PROCEDURE course_stats(IN p_course INT, OUT p_count INT, OUT p_avg DECIMAL(5,1))
BEGIN
SELECT COUNT(*), AVG(marks) INTO p_count, p_avg
FROM enrollments WHERE course_id = p_course;
END //
DELIMITER ;
CALL course_stats(2, @n, @avg);
SELECT @n AS students, @avg AS avg_marks;
students | avg_marks 3 | 75.0
Business Logic with a Transaction
DELIMITER //
CREATE PROCEDURE enroll_student(IN p_student INT, IN p_course INT)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
IF EXISTS (SELECT 1 FROM enrollments WHERE student_id = p_student AND course_id = p_course) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Already enrolled';
END IF;
INSERT INTO enrollments (student_id, course_id, marks) VALUES (p_student, p_course, NULL);
COMMIT;
END //
DELIMITER ;
Explanation: The procedure checks for a duplicate, raises a clear error if needed, and inserts inside a transaction. If anything fails, the handler rolls back so the data stays consistent. Apps simply call CALL enroll_student(4, 2);.
Call from Python
import mysql.connector
con = mysql.connector.connect(host="localhost", user="app", password="...", database="institute")
cur = con.cursor()
cur.callproc("get_students_by_city", ["Ludhiana"])
for result in cur.stored_results():
print(result.fetchall())
PostgreSQL
CREATE OR REPLACE FUNCTION students_in(p_city TEXT)
RETURNS TABLE(id INT, name TEXT) AS $$
SELECT id, name FROM students WHERE city = p_city;
$$ LANGUAGE sql;
SELECT * FROM students_in('Ludhiana');
Explanation: PostgreSQL mostly uses functions that return values or tables; CREATE PROCEDURE (with CALL) exists since version 11 for steps that manage transactions.
Procedure vs Function
| Stored procedure | Function | |
|---|---|---|
| Called with | CALL | Inside a SELECT |
| Returns | Result sets, OUT parameters | A single value or a table |
| Transactions | Can COMMIT/ROLLBACK | Usually not |
Pros and Cons
| Pros | Cons |
|---|---|
| Fewer round trips from the app | Logic split between app and database |
| Central business rules and permissions | Harder to version-control and test |
| Users can be allowed to CALL without table access | Syntax differs between databases |
Series
SQL series: SQL Basics · Advanced SQL · Views · Indexing · Stored Procedures · Database Design · SQL for Analytics · MySQL · PostgreSQL · MongoDB · NoSQL vs SQL · Interview Questions
Interview Questions
Q: Why use stored procedures?
To encapsulate multi-step database logic, reduce network calls and control permissions.
Q: What does DELIMITER do in MySQL?
Changes the statement terminator so the procedure body can contain semicolons.
Practice Exercises
- Write a procedure that returns the top N students by marks.
- Write a procedure that updates a course fee only if the new fee is positive.
Summary
Stored procedures save reusable SQL logic in the database, accept IN/OUT parameters, can wrap transactions and are called with CALL; PostgreSQL mainly uses functions.
Next: NoSQL vs SQL
Machine Learning Tutorials, Courses and Certifications