Stored Procedure
These are bits of reusable code that runs on the PostgreSQL server, to write them use use plpgsql, these cannot be ported from one database to another, and the general goal is to have fewer statements, this can cause database lock in due to the inability of porting these stored procedure.
These are like internal scripts that can be invoked, a great example would be if an application needs around 10 SQL queries to be run to perform a task, but this can be slow to process them due to the back and forth that happens, using stored procedure there would be a single point to run all the 10 SQL queries resulting in better performance
One should have a strong reason to use them
- If you have a major performance problem these are great.
- Harder to test / modify
- No database portability
Syntax (MySQL)
DELIMITER //
CREATE PROCEDURE transfer_funds(
IN from_account INT,
IN to_account INT,
IN amount DECIMAL(10,2)
)
BEGIN
START TRANSACTION;
UPDATE accounts SET balance = balance - amount WHERE id = from_account;
UPDATE accounts SET balance = balance + amount WHERE id = to_account;
COMMIT;
END //
DELIMITER ;Call it:
CALL transfer_funds(1, 2, 500.00);Parameter Modes
| Mode | Description |
|---|---|
IN | Input only — the caller passes a value in (default) |
OUT | Output only — the procedure sets a value for the caller to read |
INOUT | Both — the caller passes a value in, the procedure modifies it |
CREATE PROCEDURE get_balance(IN acct INT, OUT bal DECIMAL)
BEGIN
SELECT balance INTO bal FROM accounts WHERE id = acct;
END;Stored Procedures vs Functions
| Aspect | Stored Procedure | Function |
|---|---|---|
| Return value | Via OUT params, no direct return | Returns a value directly |
| Use in SQL | Cannot use in SELECT | Can use in SELECT, WHERE, etc. |
| Transactions | Can manage transactions (COMMIT/ROLLBACK) | Cannot manage transactions |
| Side effects | Allowed (INSERT, UPDATE, DELETE) | Allowed but discouraged |
Stored Procedures vs Triggers
| Aspect | Stored Procedure | Trigger |
|---|---|---|
| Invocation | Explicit CALL | Automatic on DML event |
| Parameters | IN, OUT, INOUT | None (uses OLD/NEW) |
| Use case | Reusable business logic | Reactive side effects |
Security
- Procedures run with the privileges of the definer by default (MySQL
DEFINER), not the caller - Can be used to implement row-level security — users call a procedure instead of accessing the table directly
- Grant
EXECUTEprivilege to users without granting direct table access