Stored Procedures

Updated · 9 min read
mediumPostgreSQL 18sqlstored-procedurescreate-procedurecallplpgsqlinterview

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 IN by default; INOUT and OUT hand values back to the caller.
  • RAISE EXCEPTION stops the procedure with your own error message, and its changes are undone.
  • Unlike a function, a procedure can COMMIT and ROLLBACK inside its body.
  • MySQL also uses CALL; SQL Server uses EXEC.

Syntax

SQL
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;
PartMeans
OR REPLACEReplace an existing procedure with the same name and parameter types
LANGUAGE plpgsqlThe 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 ... ENDThe 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:

SQL▶ Try it
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;
Output
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.

The program sends one CALL; the database runs every step of the procedure and returns

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:

SQL▶ Try it
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;
Output
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:

SQL▶ Try it
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);
Output
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:

SQL▶ Try it
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;
Output
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.

Batch one is committed and stays; batch two is rolled back and disappears

Procedures in Other Databases

DatabaseCreateRun
PostgreSQL (11+)CREATE PROCEDURE p(a INTEGER) LANGUAGE plpgsql AS $$ BEGIN ... END; $$;CALL p(1);
MySQLCREATE PROCEDURE p(IN a INT) BEGIN ... END (with DELIMITER // in the mysql client)CALL p(1);
SQL ServerCREATE PROCEDURE p @a INT AS BEGIN ... END;EXEC p @a = 1;
OracleCREATE 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 fitPoor fit
Several steps that must always run togetherBusiness rules that change weekly and need app-level tests
Batch jobs that commit in chunksLogic that needs web services, files or email
Shared rules for many programs that use one databaseTeams 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.

Procedure or Function?

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
SQL▶ Try it
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;
Output
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.

Quick check: Stored procedures

3 questions
1How do you run a PostgreSQL procedure named record_payment?
2What happens to a procedure's changes when it raises an exception?
3What can a procedure do that a function can't, in PostgreSQL?

Key Takeaways

You want toWrite
Create a procedureCREATE PROCEDURE p(a INTEGER) LANGUAGE plpgsql AS $$ BEGIN ... END; $$;
Run itCALL p(1);
Reject inputRAISE EXCEPTION 'message %', value;
Return a valueINOUT result NUMERIC DEFAULT NULL
Remove itDROP PROCEDURE p;

Was this tutorial helpful?

Lesson 84 of 115