smartyfy.mrindigi.com

Databases & SQL Master Course — 175. Stored Functions and Procedures

Lesson 175 Stored Functions and Procedures

Verification scope and lab safety

PostgreSQL 18 SQL functions and PL/pgSQL procedures only. These scripts were checked against official documentation but were not executed on that engine in the authoring environment. Every result below is a reasoned expectation, not observed output. Use a dedicated disposable local lab with the required privileges, never an existing application database. No server installation, credential changes, or external database operation is part of this lesson.

Prerequisites and objectives

Complete generated expressions, transaction errors, and least privilege. You will distinguish a value-returning function from a procedure invoked with CALL, declare a small pure function accurately, inspect a guarded procedure’s transaction behavior, and evaluate the maintenance and privilege tradeoffs of putting logic inside the database.

Choose a routine for a clear responsibility

A PostgreSQL function can be used in an expression or query and has a declared result contract. A procedure is invoked with CALL and can represent a database operation; output parameters are possible, but the procedure below uses none. Neither automatically improves simplicity, speed, or safety.

Routines can centralize shared calculations and tightly scoped data operations. They also become deployed schema dependencies requiring version control, review, tests, ownership, permissions, and observability. Avoid moving a large application workflow into the database merely to reduce the number of visible client statements.

This lesson uses a pure multiplication function and a stock-adjustment procedure. The procedure performs no internal COMMIT or ROLLBACK, so the caller retains the transaction boundary. The example does not contact external services or claim that a database routine can roll back effects outside the database.

Prepare a rollback-only local lab

Use a verified disposable PostgreSQL 18 database and an unused lab175 schema. The caller must already have authority to create these objects. Stop on a name collision. All definitions and calls are documentation-reviewed and unexecuted here; the final rollback removes the lab objects and data if the sequence is run as described.

BEGIN;
CREATE SCHEMA lab175;
CREATE TABLE lab175.stock(id integer PRIMARY KEY,qty integer NOT NULL CHECK(qty>=0));
INSERT INTO lab175.stock VALUES(1,5);
CREATE FUNCTION lab175.line_total(p_units integer,p_unit_cents integer)
RETURNS bigint LANGUAGE SQL IMMUTABLE STRICT SECURITY INVOKER
RETURN p_units::bigint*p_unit_cents;
REVOKE EXECUTE ON FUNCTION lab175.line_total(integer,integer) FROM PUBLIC;
CREATE PROCEDURE lab175.adjust_stock(IN p_id integer,IN p_delta integer)
LANGUAGE plpgsql SECURITY INVOKER AS $$
BEGIN
  UPDATE lab175.stock SET qty=qty+p_delta
  WHERE id=p_id AND qty+p_delta>=0;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'Stock adjustment rejected' USING ERRCODE='P0001';
  END IF;
END;
$$;
REVOKE EXECUTE ON PROCEDURE lab175.adjust_stock(integer,integer) FROM PUBLIC;
Reasoned routine contracts; engine execution pending
Routine Invocation Responsibility
line_total(integer,integer) SELECT or expression Return a bigint multiplication result
adjust_stock(integer,integer) CALL Apply one guarded stock change or raise a rejection
Caller transaction BEGIN/COMMIT/ROLLBACK Decide whether the complete operation is accepted

Worked practice

Exercise 1

Evaluate the pure function and check its result type.

Worked solution
SELECT lab175.line_total(3,125),pg_typeof(lab175.line_total(3,125));

The function returns three hundred seventy-five cents as bigint. Casting an operand before multiplication changes the arithmetic operation’s type; casting only after an overflowing narrower multiplication would be too late. The function’s two integer inputs keep this particular product within bigint’s representable range.

Exercise 2

Test NULL behavior and distinguish it from business validation.

Worked solution
SELECT lab175.line_total(NULL::integer,125);
SELECT lab175.line_total(-1,125);

STRICT means a NULL input produces NULL without executing the function body. It does not mean every non-NULL input is valid business data. The negative result is consistent with multiplication but may be unsuitable for an order contract, which must validate its quantity or use a differently specified routine.

Exercise 3

Call the guarded stock procedure and inspect its pending effect.

Worked solution
CALL lab175.adjust_stock(1,-2);
SELECT qty FROM lab175.stock WHERE id=1;

The UPDATE affects one row because five minus two is nonnegative. PL/pgSQL FOUND records whether the preceding UPDATE affected a row, so the rejection branch is not taken. The quantity is still part of the caller’s open transaction and can be rolled back with the rest of the lab.

Exercise 4

Reject an excessive decrement, recover, and abandon the lab.

Worked solution
SAVEPOINT rejected_adjustment;
CALL lab175.adjust_stock(1,-99);
-- Expected SQLSTATE P0001; recover explicitly.
ROLLBACK TO SAVEPOINT rejected_adjustment;
RELEASE SAVEPOINT rejected_adjustment;
SELECT qty FROM lab175.stock WHERE id=1;
ROLLBACK;

The failed precondition produces no stock change, and the procedure raises its stated error. The caller recovers through the savepoint before issuing another query. Missing identity and insufficient quantity share this simple rejection code; a richer public API needs an intentional response policy rather than inferring the cause from localized message text.

Declare planner promises honestly

IMMUTABLE tells PostgreSQL that the function’s result depends only on its inputs and is stable for the same inputs. That is appropriate for the shown bounded pure arithmetic. A function reading mutable tables, current time, or session-dependent configuration may require a different volatility category.

Volatility is a promise used by planning and execution, not a request to make an unstable function behave correctly. Mislabeling a function can lead to stale or incorrectly optimized results. STRICT is a separate NULL-handling declaration, and SECURITY INVOKER is a separate privilege decision.

Do not use a pure function’s convenient reuse as evidence that every business constraint has moved into it. A function can calculate a negative value correctly while the application must reject that value for a particular workflow.

Keep privilege and transaction boundaries explicit

SECURITY INVOKER uses the caller’s privileges. SECURITY DEFINER is a different and more sensitive design requiring careful ownership, search-path hardening, qualification, and execution grants. The examples explicitly use invoker behavior and schema-qualified table references rather than teaching elevated execution as a shortcut.

PostgreSQL commonly grants routine execution to PUBLIC by default. The setup revokes that broad grant only on the new disposable routines so an operational design must choose its intended callers deliberately. No login roles or credentials are created here, and the owner performs the lab calls.

Procedures can perform transaction control only in supported calling contexts and subject to other restrictions. In particular, a CALL inside an explicit transaction cannot let the procedure independently end that transaction. This procedure avoids transaction control entirely so its role in the caller’s atomic unit is clear.

Maintain routines as application interfaces

Record parameter types, result shape, NULL behavior, allowed ranges, error codes, side effects, and required privileges. Test both successful and rejected calls under the intended runtime identity. A routine signature can be stable while a changed body alters important business meaning.

Version definitions through reviewed migrations and inspect dependencies before changing signatures or return types. Avoid hidden dynamic SQL unless its identifiers and values follow the same allowlist and binding rules as application queries. Database placement does not make concatenated untrusted text safe.

Pitfalls and summary

Choose routines for bounded responsibilities, declare volatility and NULL behavior accurately, and preserve explicit caller authority and transaction ownership. Treat definitions, privileges, error contracts, and tests as maintained code. These PostgreSQL examples remain unexecuted until a verified local engine is available.

Knowledge check

Question 1

Which statement invokes the stock procedure in PostgreSQL?

  1. SELECT lab175.adjust_stock(1,-2)
  2. EXECUTE lab175.adjust_stock(1,-2)
  3. CALL lab175.adjust_stock(1,-2)
  4. SELECT * FROM lab175.adjust_stock(1,-2)
Answer and explanation

C. CALL invokes a procedure; SELECT forms are function calls, while SQL EXECUTE runs a prepared statement.

Question 2

What does STRICT establish for line_total?

  1. NULL arguments raise a validation exception
  2. NULL arguments are replaced with each type’s default value
  3. All non-NULL arguments must satisfy positive-quantity business rules
  4. A NULL input returns NULL without executing its body
Answer and explanation

D. STRICT controls NULL handling, not domain validation or automatic substitution.

Question 3

Why is IMMUTABLE appropriate for this function?

  1. It has no writes, so any reads of changing tables would also be immutable
  2. Its arithmetic result depends only on the supplied integer inputs
  3. Its result is guaranteed stable only within one SQL statement
  4. The declaration snapshots changing dependencies for future calls
Answer and explanation

B. Pure input-dependent arithmetic meets the promise; read-only access alone does not make a function immutable.

Question 4

Who controls acceptance of the successful stock adjustment here?

  1. CALL automatically commits its procedure’s UPDATE
  2. Returning normally creates an implicit procedure-level commit
  3. The procedure’s BEGIN block starts a separate transaction
  4. The caller’s surrounding transaction
Answer and explanation

D. The PL/pgSQL block contains no transaction control; its changes remain pending in the caller’s transaction.

Question 5

Which privilege behavior do these SECURITY INVOKER routines use?

  1. The caller’s privileges for the underlying operation
  2. The routine owner’s privileges for every underlying operation
  3. The table owner’s privileges regardless of the caller
  4. EXECUTE permission alone replaces required table privileges
Answer and explanation

A. Invoker security does not elevate the caller or replace the relevant underlying-object permissions.

Dialect verification notes

The target is PostgreSQL 18 SQL functions and PL/pgSQL procedures. Engine execution remains pending. SQLite was not used as a substitute for executing these dialect-specific scripts. Record actual server version, session settings, results, and errors when running the local lab. Python is not a learner prerequisite.

Primary references