Knowledge base / SQL

Stored procedures in PostgreSQL: parameters, CALL and results

A synthetic task count demonstrates a procedure contract without mixing PostgreSQL, MySQL and T-SQL syntax.

Kajo RudzińskiPublished Updated 4 min read

A mechanical module connects an input funnel, a database cylinder and an output tray.

I treat a stored procedure as a named database object with defined inputs, behaviour and outputs. Wrapping a query in a procedure does not establish that it will be faster or more secure. This entry uses PostgreSQL 18 and PL/pgSQL. Other engines have their own creation and invocation rules. I do not combine them into a supposedly universal SQL syntax.

Distinguish a procedure from a function

The PostgreSQL documentation defines procedures with CREATE PROCEDURE and invokes them with CALL. A procedure has no function-style RETURNS clause, but can pass data through output parameters. A function can be part of a query. A universal comparison table claiming that functions only execute SELECT would be misleading across database systems.

A simple read may only need an ordinary query or a function. I deliberately use a procedure here to explain its contract and result handling. I am not claiming that counting three records requires this structure in a real project. Choose the database object according to the interface an application or process needs, rather than selecting whichever term sounds more advanced.

Use small data with an explicit scope

This synthetic material belongs in a separate training database. The temporary table exists for the session; the procedure definition is a regular database object. Following the fragments requires the same session containing that table and the necessary object-creation privileges. The described results follow from the documentation and small input table. I do not claim to have executed the code.

CREATE TEMP TABLE demo_tasks (
    task_id integer PRIMARY KEY,
    status text NOT NULL
);

INSERT INTO demo_tasks VALUES
    (1, 'open'),
    (2, 'done'),
    (3, 'open');

There are two open tasks and one done task. No real users, accounts or business transactions are involved. The procedure only counts tasks by status. Its contract says that NULL as the status is an invalid call, while a status absent from the table returns zero. Distinguishing invalid input from an empty result helps the caller interpret what happened.

Define parameters and a body

CREATE PROCEDURE specifies parameter modes. p_status is an input, while p_total is INOUT. Its incoming value is replaced by the count in this example. The p_ prefix helps distinguish parameters from columns.

CREATE PROCEDURE count_demo_tasks(
    IN p_status text,
    INOUT p_total bigint
)
LANGUAGE plpgsql
AS $$
BEGIN
    IF p_status IS NULL THEN
        RAISE EXCEPTION 'Status is required';
    END IF;

    SELECT count(*) INTO p_total
    FROM demo_tasks AS t
    WHERE t.status = p_status;
END;
$$;

Dollar quoting delimits the definition string. BEGIN and END form a PL/pgSQL block; they do not begin and commit a transaction here. PL/pgSQL SELECT INTO assigns a result to a variable, in this case p_total. It does not create a new table. COUNT returns the number of matching rows, including zero if none meets the condition.

Call the procedure and receive its result

CALL count_demo_tasks('open', NULL);

CALL returns a result row for output parameters. Here, p_total should be 2 because tasks 1 and 3 match. For 'done', I expect 1; for 'unknown', zero. NULL supplies the INOUT argument, which the procedure body overwrites with the count. I do not omit that argument merely because I am interested in its output role.

Passing NULL as the first argument triggers the missing-status condition. RAISE EXCEPTION reports an error, normally aborting the current transaction. It is not converted into a successful zero result. An empty string is not rejected by this particular definition; with our data, it matches nothing. A different validation rule should first be stated explicitly in the contract.

An input gate accepts a solid cube while a separate closed path blocks a hollow one.

Transaction control has conditions

Our procedure performs no internal commit or rollback, so it can be invoked within an explicit transaction. That does not mean COMMIT can be added to any procedure. The PL/pgSQL transaction documentation specifies allowed contexts and call-stack restrictions. CALL inside an explicit transaction block does not permit the procedure to end that transaction itself.

I have removed the older transfer example that checked @@ERROR only after two statements. Microsoft documents that this T-SQL value resets after every statement. Checking the second does not establish whether the first succeeded. I do not turn that fragment into a financial-transaction guide. A small counter can explain a procedure without implying a complete accounting mechanism.

Review the contract before project use

I document parameter names and types, the no-match result and invalid-input behaviour. I also establish who owns the transaction and which objects must exist. Default SECURITY INVOKER execution uses the caller’s privileges; packaging code in a procedure does not itself grant table access. A different permission model needs a separate design decision, rather than being silently added to a basic exercise.

On paper, add task 4 with status done and predict the new count. Then compare zero for an absent status with an error for NULL. If you can explain the difference and identify how p_total reaches the caller, you understand the basic contract. Continue with COUNT and window functions, keeping each example’s dialect explicit.

Key takeaways

How do I call this procedure?

In PostgreSQL, use CALL count_demo_tasks with the status and INOUT arguments. EXEC in the older English text was T-SQL syntax.

Is a procedure always faster than a query?

No. Encapsulating logic in a procedure does not replace examining the query and its execution plan.

Can a procedure execute COMMIT?

PostgreSQL permits that in specified contexts. A procedure invoked by CALL inside an explicit transaction block cannot end that transaction itself.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.