23 Feb 2024
Intermediate
In PostgreSQL, both procedures and functions are database objects that encapsulate a series of SQL and procedural statements. However, they have some differences in terms of their behavior and usage:
-
Return Type:
- Function: Functions must have a specified return type. They return a value and can be used in SQL queries like any other expression.
- Procedure: Procedures do not have a return type. They typically perform an action or a series of actions without returning a value directly.
-
Usage in Queries:
- Function: Functions can be called from within SQL queries and used in expressions. They can be part of a SELECT statement, WHERE clause, or used in other SQL expressions.
- Procedure: Procedures are generally called using the CALL statement. They are not used in the same way as functions within SQL queries.
-
Transaction Control:
- Function: Functions can be part of a transaction and can participate in the transaction control statements (e.g., COMMIT or ROLLBACK).
- Procedure: Procedures can also be part of a transaction, and they can include transaction control statements. However, procedures are often used for encapsulating a series of actions that may include multiple transactions.
-
Atomicity:
- Functions are atomic, meaning they are executed within a single transaction and cannot be interrupted.
- Procedures are not atomic and can be interrupted or rolled back.
-
Data Modification:
- Functions can modify data within the database.
- Procedures can also modify data within the database.
Example illustrating the differences:
-- Function example
CREATE FUNCTION get_employee_count() RETURNS INTEGER AS $$
DECLARE
emp_count INTEGER;
BEGIN
SELECT COUNT(*) INTO emp_count FROM employees;
RETURN emp_count;
END;
$$ LANGUAGE plpgsql;
-- Procedure example
CREATE PROCEDURE update_employee_salary(amount INT) AS $$
BEGIN
UPDATE employees SET salary = salary + amount;
END;
$$ LANGUAGE plpgsql;
To call the function, you would use it in a SQL query:
SELECT get_employee_count();
To call the procedure, you would use the CALL statement:
CALL update_employee_salary(500);
Summary: functions are primarily used to compute and return values, while procedures are used to perform actions or tasks.