Skip to content
IT glossary
DatabasesUpdated December 3, 2026

Stored procedure

Хранимая процедура

This is a named program saved in a database and run on the database server. An application can call it to perform a task, such as updating several tables, without sending each SQL statement separately.

Also known as: триггер, trigger

What it is

A stored procedure gives a database operation a name and a set of parameters. For example, a billing service can call a procedure with an invoice ID instead of sending separate statements to update the invoice and insert a record into its history. The procedure lives in the database, so other clients can call the same operation without duplicating its SQL.

How it works

You typically define a procedure with CREATE PROCEDURE and deploy it through a database migration. The database checks whether the caller has permission to execute it, then runs its body on the server. Depending on the database engine, a procedure can take input parameters, pass values back through output parameters, or return result sets. PostgreSQL and MySQL use CALL to invoke procedures; SQL Server uses EXEC or EXECUTE.

Example: closing an order in PostgreSQL

Assume an orders table with id, status, and closed_at columns. This procedure closes an order only if it is open:

CREATE PROCEDURE close_order(p_order_id bigint)
LANGUAGE SQL
AS $$
  UPDATE orders
  SET status = 'closed', closed_at = CURRENT_TIMESTAMP
  WHERE id = p_order_id AND status = 'open';
$$;

CALL close_order(42);

Calling it again won't overwrite the original closing timestamp, because the row no longer matches status = 'open'. A plain UPDATE would be enough for this one step. The case for a procedure gets stronger if every client must follow the same multi-step rule, such as adding a history record only when the status actually changes.

When to use one

Stored procedures are useful for batch jobs and shared operations that work mainly with data in one database. Combining statements in one call can cut network round trips, but the statements still depend on suitable indexes, execution plans, and locking behavior. There's also a deployment cost: keep procedure definitions in version control and test changes against the database as you would other application code. Moving to another database engine may require rewriting them.

Interview questions

Be ready to distinguish a procedure from a function and a trigger. In PostgreSQL, you invoke a procedure with a standalone CALL, whereas a function can appear in a SQL expression, such as in a SELECT list. A trigger is not another name for a stored procedure: it fires automatically in response to a configured event, such as an update to a table. Also, don't assume that calling a procedure creates a separate transaction or commits its changes. In PostgreSQL, a procedure invoked by CALL inside an explicit transaction block cannot issue its own COMMIT or ROLLBACK.