Stored Procedures
A stored procedure in SQL is a named set of SQL statements saved inside the database, which a program runs with one command such as CALL record_payment(102, 4, 150.00, 'card'). It is used when several steps must always happen together and in the same way: check the input, insert a row, update a total, and perhaps commit. Instead of every program repeating those steps, they all call the procedure. In this lesson, we will create a procedure for recording fee payments, pass it parameters, make it reject bad input with a clear message, and control transactions from inside it.
In One Minute
CREATE PROCEDURE name(params) LANGUAGE plpgsql AS $$ ... $$stores the steps;CALL name(args)runs them.- Parameters are
INby default;INOUTandOUThand values back to the caller. RAISE EXCEPTIONstops the procedure with your own error message, and its changes are undone.- Unlike a function, a procedure can
COMMITandROLLBACKinside its body. - MySQL also uses
CALL; SQL Server usesEXEC.
Syntax
CREATE [OR REPLACE] PROCEDURE procedure_name (
param_name data_type [, ...]
)
LANGUAGE plpgsql
AS $$
BEGIN
-- SQL statements
END;
$$;
CALL procedure_name (value [, ...]);
DROP PROCEDURE procedure_name;| Part | Means |
|---|---|
OR REPLACE | Replace an existing procedure with the same name and parameter types |
LANGUAGE plpgsql | The body is PL/pgSQL, PostgreSQL's procedural language (LANGUAGE sql also works for plain SQL steps) |
$$ ... $$ | Dollar quotes around the body, so quotes inside it need no escaping |
BEGIN ... END | The block of statements the procedure runs |
Creating and Calling a Procedure
Recording a payment always means the same insert with the same default dates. A procedure keeps it in one place:
CREATE PROCEDURE record_payment(
p_student INTEGER,
p_course INTEGER,
p_amount NUMERIC,
p_method TEXT
)
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (p_student, p_course, p_amount, DATE '2026-01-05', DATE '2026-01-05', p_method);
END;
$$;
CALL record_payment(102, 4, 150.00, 'card');
SELECT payment_id, student_id, course_id, amount_usd, method
FROM payments
WHERE student_id = 102;CREATE PROCEDURE
CALL
payment_id | student_id | course_id | amount_usd | method
------------+------------+-----------+------------+--------
8 | 102 | 4 | 150.00 | card
(1 row)Explanation: CREATE PROCEDURE only stores the code; nothing runs until CALL. The call inserts Advitha's first payment, 150.00 toward SQL Basics, as payment 8. The parameter names start with p_ so they can't be confused with column names such as student_id.
Rejecting Bad Input
RAISE EXCEPTION stops a procedure with an error you write yourself. Any changes the procedure made are undone, just as with any failing statement. Here the procedure checks that the student is enrolled before inserting, and gives a clear message instead of a foreign key error:
CREATE PROCEDURE record_payment(p_student INTEGER, p_course INTEGER, p_amount NUMERIC, p_method TEXT)
LANGUAGE plpgsql
AS $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM enrollments
WHERE student_id = p_student AND course_id = p_course) THEN
RAISE EXCEPTION 'student % is not enrolled in course %', p_student, p_course
USING HINT = 'Enroll the student before recording a payment.';
END IF;
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (p_student, p_course, p_amount, DATE '2026-01-05', DATE '2026-01-05', p_method);
END;
$$;
CALL record_payment(103, 6, 250.00, 'card');
SELECT count(*) AS payments FROM payments;CREATE PROCEDURE
ERROR: student 103 is not enrolled in course 6
HINT: Enroll the student before recording a payment.
payments
----------
7
(1 row)Explanation: Navika (103) isn't enrolled in Git Basics (course 6), so the procedure raises its own error. Each % in the message is replaced by the next value. USING HINT adds the HINT line. No payment was added: the count is still 7.
Parameters That Return Values
An INOUT parameter carries a value in and back out. CALL then returns a row with the final values:
CREATE PROCEDURE course_balance(
p_student INTEGER,
p_course INTEGER,
INOUT p_owed NUMERIC DEFAULT NULL
)
LANGUAGE plpgsql
AS $$
BEGIN
SELECT c.fee_usd - COALESCE(sum(p.amount_usd), 0)
INTO p_owed
FROM courses AS c
LEFT JOIN payments AS p ON p.course_id = c.course_id AND p.student_id = p_student
WHERE c.course_id = p_course
GROUP BY c.fee_usd;
END;
$$;
CALL course_balance(101, 2);
CALL course_balance(p_student => 102, p_course => 4);CREATE PROCEDURE
p_owed
--------
0.00
(1 row)
p_owed
--------
400.00
(1 row)Explanation: Srihitha paid 250.00 twice toward Java OOP's 500.00 fee, so she owes 0.00. Advitha owes all 400.00 for SQL Basics. SELECT ... INTO p_owed stores the query's result in the parameter. The second call uses named arguments (name => value), which are clearer when a procedure has many parameters. DEFAULT NULL lets the caller leave out p_owed.
Transactions Inside Procedures
A procedure can commit or roll back its own work part of the way through, something a function can't do:
CREATE PROCEDURE load_two_batches()
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 4, 100.00, DATE '2026-01-05', DATE '2026-01-05', 'card');
COMMIT;
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 4, 999.00, DATE '2026-01-05', DATE '2026-01-05', 'card');
ROLLBACK;
END;
$$;
CALL load_two_batches();
SELECT amount_usd FROM payments WHERE student_id = 102;CREATE PROCEDURE
CALL
amount_usd
------------
100.00
(1 row)Explanation: The first batch was committed, so its 100.00 payment stays. The second was rolled back, so 999.00 is gone. This is useful for long jobs that process data in batches and commit each one, like the batched updates in Writing Fast Queries. It works only when the procedure is called directly with CALL, not from inside an explicit BEGIN ... COMMIT block.
Procedures in Other Databases
| Database | Create | Run |
|---|---|---|
| PostgreSQL (11+) | CREATE PROCEDURE p(a INTEGER) LANGUAGE plpgsql AS $$ BEGIN ... END; $$; | CALL p(1); |
| MySQL | CREATE PROCEDURE p(IN a INT) BEGIN ... END (with DELIMITER // in the mysql client) | CALL p(1); |
| SQL Server | CREATE PROCEDURE p @a INT AS BEGIN ... END; | EXEC p @a = 1; |
| Oracle | CREATE OR REPLACE PROCEDURE p(a NUMBER) IS BEGIN ... END; | EXEC p(1); in SQL*Plus, or BEGIN p(1); END; |
Tabs showing each database's version are coming to this course.
When to Use Procedures
| Good fit | Poor fit |
|---|---|
| Several steps that must always run together | Business rules that change weekly and need app-level tests |
| Batch jobs that commit in chunks | Logic that needs web services, files or email |
| Shared rules for many programs that use one database | Teams with no way to version and review database code |
Keep procedures in version control like any other code, and create them with migration scripts, as Schema Migrations shows later in the course.
Common Mistakes
Parameter names that match column names. WHERE student_id = student_id compares the column with itself. Prefix parameters, for example p_student.
Calling a procedure with SELECT. Procedures run with CALL; functions run inside SELECT.
Using a procedure just to return a value. A function is simpler and works inside queries.
COMMIT inside a procedure called within a transaction block. It fails with "invalid transaction termination". Call it on its own.
Interview Corner
What is a stored procedure?
A named block of SQL and procedural code stored in the database and run with CALL (or EXEC in SQL Server). It groups steps so every program runs them the same way.
What's the difference between a stored procedure and a function?
A function returns a value and can be used inside SELECT. A procedure is called on its own with CALL, returns values only through OUT/INOUT parameters, and in PostgreSQL can commit and roll back transactions.
What are the advantages of stored procedures?
Shared rules in one place, fewer round trips between program and database, and permissions that let users run the procedure without direct access to the tables. The costs are harder testing, versioning and portability.
Practice
Challenge: Create a procedure drop_enrollment(p_student, p_course) that sets an enrollment's status to 'dropped', and raises an error if the enrollment doesn't exist. Drop Advitha (102) from Java Basics (course 1) and show her enrollments.
Show solution
CREATE PROCEDURE drop_enrollment(p_student INTEGER, p_course INTEGER)
LANGUAGE plpgsql
AS $$
BEGIN
UPDATE enrollments
SET status = 'dropped'
WHERE student_id = p_student AND course_id = p_course;
IF NOT FOUND THEN
RAISE EXCEPTION 'no enrollment for student % in course %', p_student, p_course;
END IF;
END;
$$;
CALL drop_enrollment(102, 1);
SELECT student_id, course_id, status
FROM enrollments
WHERE student_id = 102
ORDER BY course_id;CREATE PROCEDURE
CALL
student_id | course_id | status
------------+-----------+---------
102 | 1 | dropped
102 | 4 | active
(2 rows)FOUND is a built-in PL/pgSQL variable that's true when the last statement affected at least one row. Here the update matched, so no error was raised and Java Basics is now dropped.
Key Takeaways
| You want to | Write |
|---|---|
| Create a procedure | CREATE PROCEDURE p(a INTEGER) LANGUAGE plpgsql AS $$ BEGIN ... END; $$; |
| Run it | CALL p(1); |
| Reject input | RAISE EXCEPTION 'message %', value; |
| Return a value | INOUT result NUMERIC DEFAULT NULL |
| Remove it | DROP PROCEDURE p; |
Was this tutorial helpful?