Stored Procedures and Functions
How to store reusable logic in the database: SQL and PL/pgSQL functions, parameters with defaults and named notation, functions that return tables, volatility and STRICT, procedures with CALL and COMMIT, SECURITY DEFINER, overloading and replacing functions, and when logic belongs in the database.
kvi5hnuCode Sprout team member11 min readOn this page
Articles 62 and 63 ran procedural code in anonymous DO blocks, which disappear once they've run. To reuse code, store it in the database as a function or a procedure. Any query, application or report can then call it, with a single definition to test, secure and change.
This article covers creating functions in plain SQL and in PL/pgSQL, passing parameters, returning single values and whole tables, telling the planner how a function behaves, procedures that control transactions, running code with its owner's privileges, and the debate about how much logic should live in the database.
Functions in SQL
The simplest functions are written in plain SQL:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A SQL function: the body is just a query
CREATE FUNCTION order_total(p_order_id INTEGER)
RETURNS NUMERIC
LANGUAGE sql
STABLE
RETURN (SELECT COALESCE(SUM(qty * unit_price), 0)
FROM order_items WHERE order_id = p_order_id);
-- Parameters with defaults, called by position or by name
CREATE FUNCTION line_price(p_qty INTEGER, p_unit NUMERIC, p_discount NUMERIC DEFAULT 0)
RETURNS NUMERIC
LANGUAGE sql
IMMUTABLE
RETURN round(p_qty * p_unit * (1 - p_discount), 2);
SELECT order_id, order_total(order_id) AS total
FROM orders ORDER BY order_id;
SELECT line_price(2, 34.50) AS no_discount,
line_price(2, 34.50, 0.10) AS positional,
line_price(p_unit => 34.50, p_qty => 2, p_discount => 0.25) AS named;
order_id | total
----------+--------
101 | 297.99
102 | 69.00
103 | 154.45
104 | 489.00
105 | 54.00
106 | 16.00
(6 rows)
no_discount | positional | named
-------------+------------+-------
69.00 | 62.10 | 51.75
(1 row)
CREATE FUNCTION name(parameters) RETURNS typedeclares the function's signature.LANGUAGE sqlsays the body is SQL.- The
RETURN expressionbody, available since PostgreSQL 14, is the SQL standard form for a function that computes one value.order_totalreturns a scalar subquery's result. - A function can be used anywhere an expression can: in
SELECTlists,WHEREconditions,ORDER BYand other functions.order_total(order_id)runs for each order. DEFAULTmakes a parameter optional:line_price(2, 34.50)uses a discount of 0.- Named notation,
p_unit => 34.50, passes arguments by name in any order, which makes calls with several numeric arguments much easier to read. It can be mixed with positional arguments, as long as the positional ones come first.
The older body syntax, AS $$ SELECT ... $$, still works and is common in existing code. The standard forms, RETURN and BEGIN ATOMIC, are checked when the function is created, so a mistyped column fails immediately rather than on first use, and the database tracks the tables they depend on, like a view's (article 56).
Functions that return tables
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A function returning a table, with a standard SQL body (BEGIN ATOMIC)
CREATE FUNCTION customer_orders(p_customer_id INTEGER)
RETURNS TABLE (order_id INTEGER, placed_on DATE, status TEXT, total NUMERIC)
LANGUAGE sql
STABLE
BEGIN ATOMIC
SELECT o.order_id, o.placed_on, o.status, SUM(oi.qty * oi.unit_price)
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id = p_customer_id
GROUP BY o.order_id, o.placed_on, o.status
ORDER BY o.placed_on;
END;
-- Used like a table...
SELECT * FROM customer_orders(1);
-- ...and once per row with LATERAL
SELECT c.name, co.order_id, co.total
FROM customers c
CROSS JOIN LATERAL customer_orders(c.customer_id) AS co
WHERE c.city = 'Leeds'
ORDER BY c.name, co.order_id;
order_id | placed_on | status | total
----------+------------+-----------+--------
101 | 2026-03-02 | shipped | 297.99
103 | 2026-03-09 | delivered | 154.45
(2 rows)
name | order_id | total
------------+----------+-------
Ben Okafor | 102 | 69.00
(1 row)
RETURNS TABLE (...) declares the columns of the result, and the function is used in FROM like a table. customer_orders(1) lists Asha's orders with their totals. A BEGIN ATOMIC ... END body holds one or more SQL statements, and the last one's result is returned.
Combined with LATERAL (article 23), the function runs once for each customer row, and its rows are joined to that customer. Leeds has two customers, but only Ben has orders, and CROSS JOIN LATERAL drops Eli, who has none. LEFT JOIN LATERAL ... ON true would keep Eli.
A table-returning function is like a view with parameters. For a fixed query, a view is simpler. When the query needs arguments, a function is the tool. Simple SQL functions like this one can be inlined: the planner substitutes the function's query into the calling query and optimizes the whole thing, as it does for views. PL/pgSQL functions are never inlined: the planner treats them as black boxes, and by default guesses they return 1,000 rows. ROWS 20 in the definition gives a better estimate.
Other return types: SETOF type returns many values or rows of an existing type, such as SETOF products. RETURNS void returns nothing, for functions called only for their effects. OUT parameters return several values without declaring a type: CREATE FUNCTION stats(OUT n INTEGER, OUT total NUMERIC) returns one row with two columns.
Volatility and STRICT

Every function has a volatility category, which tells the planner what it may assume:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- Volatility tells the planner what a function may do
CREATE FUNCTION sku_prefix_volatile(p_sku TEXT) RETURNS TEXT
LANGUAGE plpgsql -- VOLATILE, the default
AS $$ BEGIN RETURN upper(split_part(p_sku, '-', 1)); END $$;
CREATE FUNCTION sku_prefix(p_sku TEXT) RETURNS TEXT
LANGUAGE plpgsql IMMUTABLE STRICT
AS $$ BEGIN RETURN upper(split_part(p_sku, '-', 1)); END $$;
CREATE TABLE skus (sku TEXT);
INSERT INTO skus VALUES ('ten-0001'), ('lgt-0002'), (NULL);
-- Index expressions must be IMMUTABLE: same input, same output, forever
CREATE INDEX ON skus (sku_prefix_volatile(sku));
CREATE INDEX skus_prefix_ix ON skus (sku_prefix(sku));
-- STRICT: a NULL argument returns NULL without running the body
SELECT sku, sku_prefix(sku) AS prefix FROM skus ORDER BY sku;
SELECT proname, provolatile, proisstrict
FROM pg_proc WHERE proname LIKE 'sku_prefix%' ORDER BY proname;
psql:/workspace/solution.sql:76: ERROR: functions in index expression must be marked IMMUTABLE
sku | prefix
----------+--------
lgt-0002 | LGT
ten-0001 | TEN
(null) | (null)
(3 rows)
proname | provolatile | proisstrict
---------------------+-------------+-------------
sku_prefix | i | t
sku_prefix_volatile | v | f
(2 rows)
IMMUTABLE: the result depends only on the arguments, now and forever.sku_prefixqualifies. Only immutable functions are allowed in index expressions (article 55) and generated columns, because the stored values must never become wrong.STABLE: the result can't change within a single statement, but may change between statements. Functions that read tables, such asorder_total, or usenow()or session settings, are stable.VOLATILE, the default: anything goes, including returning different values each call (random()) or changing data. The planner calls it again for every row and avoids optimizations that assume otherwise.
The index on sku_prefix_volatile is refused because it wasn't declared immutable. The planner can't check whether your label is true. Declaring a function IMMUTABLE when it reads a table or depends on a setting such as the time zone can make queries return wrong results and indexes contain wrong entries. Label each function as strictly as is true, and no stricter.
STRICT (also written RETURNS NULL ON NULL INPUT) means "if any argument is NULL, the result is NULL": the function isn't even called. The NULL SKU gets a NULL prefix. The catalog pg_proc shows each function's settings, i, s or v for volatility.
Procedures
A procedure is created with CREATE PROCEDURE and run with CALL. It doesn't return a value the way a function does, though INOUT and, since PostgreSQL 14, OUT parameters can pass values back. Its distinctive power is transaction control: a procedure called on its own can COMMIT and ROLLBACK as it runs.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A procedure: called with CALL, can commit as it goes
CREATE TABLE archived_orders (LIKE orders);
CREATE PROCEDURE archive_orders(p_before DATE, INOUT p_moved INTEGER DEFAULT 0)
LANGUAGE plpgsql
AS $$
DECLARE
r RECORD;
BEGIN
FOR r IN SELECT order_id FROM orders
WHERE placed_on < p_before AND status = 'cancelled'
ORDER BY order_id
LOOP
INSERT INTO archived_orders SELECT * FROM orders WHERE order_id = r.order_id;
DELETE FROM order_items WHERE order_id = r.order_id;
DELETE FROM orders WHERE order_id = r.order_id;
p_moved := p_moved + 1;
COMMIT; -- each order is its own transaction
END LOOP;
END
$$;
CALL archive_orders(DATE '2026-04-01');
SELECT order_id, status FROM archived_orders;
SELECT COUNT(*) AS orders_left FROM orders;
p_moved
---------
1
(1 row)
order_id | status
----------+-----------
105 | cancelled
(1 row)
orders_left
-------------
5
(1 row)
archive_orders moves cancelled orders placed before a date into archived_orders, deleting their lines and the orders themselves. It commits after each order, so a long batch job doesn't hold one huge transaction open (article 60), and work already done survives if a later order fails. The INOUT parameter reports how many orders were moved: one, order 105.
Functions can't do this: a function always runs inside the caller's statement and transaction. Transaction control in a procedure also works only when it's called directly by CALL, not from inside an explicit transaction block or a function.
| Function | Procedure | |
|---|---|---|
| called with | an expression: SELECT f(...) | CALL p(...) |
| returns | a value, a row or a table | nothing, except INOUT/OUT parameters |
| usable in queries | yes | no |
COMMIT / ROLLBACK inside | no | yes, when called directly |
Other databases draw the line similarly. SQL Server procedures (and MySQL's) can return result sets directly with a SELECT, which makes them the usual way applications fetch data there, and EXEC calls them. Oracle groups related procedures, functions, types and variables into packages, with a public specification and a private body, a much-loved feature with no direct PostgreSQL equivalent (schemas are the nearest substitute). MySQL supports procedures and functions with its own syntax, and CALL.
Running with the owner's privileges
By default, a function runs with the privileges of the caller: SECURITY INVOKER. SECURITY DEFINER makes it run with the privileges of its owner, much like a view:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- SECURITY DEFINER: the function runs with its owner's privileges
CREATE ROLE kiosk NOLOGIN; -- may not read customers directly
CREATE FUNCTION customer_greeting(p_customer_id INTEGER)
RETURNS TEXT
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = public, pg_temp -- don't let callers redirect table names
RETURN (SELECT 'Welcome back, ' || split_part(name, ' ', 1) || '!'
FROM customers WHERE customer_id = p_customer_id);
REVOKE EXECUTE ON FUNCTION customer_greeting(INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION customer_greeting(INTEGER) TO kiosk;
SET ROLE kiosk;
SELECT customer_greeting(3);
SELECT name FROM customers WHERE customer_id = 3;
RESET ROLE;
DROP OWNED BY kiosk;
DROP ROLE kiosk;
customer_greeting
---------------------
Welcome back, Chen!
(1 row)
psql:/workspace/solution.sql:79: ERROR: permission denied for table customers
The kiosk role can't read customers, but it can call customer_greeting, which returns only a greeting built from the first name. The function is a narrow, controlled doorway into the table, the stored-code version of least privilege (article 58).
Security definer functions need care, because they run with more power than their callers:
- Set
search_pathin the function's definition, as here. Otherwise a caller could create their owncustomerstable or function in a schema earlier in their search path and trick the function into using it. - Revoke
EXECUTEfromPUBLIC, which every new function grants by default, and grant it only to the roles that need it. - If the function builds dynamic SQL, it must be safe from injection (articles 59 and 66).
Managing functions
CREATE OR REPLACE FUNCTIONchanges the body while keeping privileges and dependent objects. It can't change the return type or the parameter names. For that, drop and recreate. Changing the parameter types doesn't fail: it creates a second, overloaded function alongside the old one, so drop the old signature explicitly.- Overloading: functions with the same name but different parameter types are separate functions.
DROP FUNCTIONandGRANTtherefore name the parameter types, as incustomer_greeting(INTEGER). Overloading combined with defaults can make calls ambiguous, so use it sparingly. - Keep function definitions in version-controlled migration files (article 53), like any other schema change.
\dfand\sf namein psql list functions and show a function's source.
How much logic belongs in the database?
This is one of the long-running debates in software. Arguments for putting logic in functions and procedures:
- Fewer round trips. A procedure that runs ten statements makes one network call instead of ten.
- One source of truth. Rules enforced in the database apply to every application, script and person that touches the data.
- Security. Callers can be limited to specific operations instead of whole tables.
And against:
- Harder to develop and test. Database code has weaker tooling for debugging, testing, code review and deployment than mainstream languages, although tools such as pgTAP help.
- Harder to scale. Application servers scale out easily, while the database is usually the shared, hardest-to-scale component. CPU-heavy logic in the database competes with queries.
- Portability. PL/pgSQL, PL/SQL and T-SQL are all different, so procedural code ties you to one database.
A pragmatic middle ground used by many teams: enforce data integrity in the database with constraints, and triggers where needed (article 65); use functions for data-heavy operations that benefit from running next to the data, and for controlled access; and keep business workflows, integrations and presentation in the application.
Oracle packages
Oracle groups related procedures, functions, types and variables into a package: a specification declaring the public parts and a body implementing them.
-- Oracle
CREATE OR REPLACE PACKAGE shop_pkg AS
PROCEDURE restock(p_product_id NUMBER, p_qty NUMBER);
FUNCTION in_stock(p_product_id NUMBER) RETURN BOOLEAN;
END shop_pkg;
/
CREATE OR REPLACE PACKAGE BODY shop_pkg AS
g_restock_count NUMBER := 0; -- private, per-session state
PROCEDURE log_restock IS -- private: not in the spec
BEGIN
g_restock_count := g_restock_count + 1;
END;
PROCEDURE restock(p_product_id NUMBER, p_qty NUMBER) IS
BEGIN
UPDATE products SET stock = stock + p_qty WHERE product_id = p_product_id;
log_restock;
END;
FUNCTION in_stock(p_product_id NUMBER) RETURN BOOLEAN IS
v_stock NUMBER;
BEGIN
SELECT stock INTO v_stock FROM products WHERE product_id = p_product_id;
RETURN v_stock > 0;
END;
END shop_pkg;
/
-- Called as shop_pkg.restock(3, 10)
Packages give a public interface with private helpers, package-level variables that keep their values for the whole session, and fewer recompilations: callers depend only on the specification, so changing the body doesn't invalidate them. PostgreSQL has no packages. Schemas group related functions (shop.restock(...)), and session state can be kept in custom settings with set_config and current_setting. The orafce extension and some PostgreSQL-compatible products emulate packages for migrations from Oracle.
What's current
- PostgreSQL 14 added SQL-standard function bodies (
RETURNandBEGIN ATOMIC) andOUTparameters for procedures. - PostgreSQL 17 made maintenance operations run functions with a safe
search_path, which matters for functions used in index expressions and materialized views (article 56). - MySQL 9.0 added stored functions and procedures written in JavaScript, in its Enterprise Edition, alongside the traditional SQL syntax.
Common questions
What's the difference between a function and a procedure?
A function returns a value and can be used in queries, but can't commit. A procedure is run with CALL and can commit and roll back as it goes.
Should I write functions in SQL or PL/pgSQL? SQL, when the function is a single query or expression: it's simpler and can be inlined into the calling query. PL/pgSQL, when you need variables, loops, conditions or error handling.
Why was my function not allowed in an index?
Index expressions require IMMUTABLE functions. Declare it immutable only if its result truly depends on nothing but its arguments.
How do I change a function's parameters?
Drop it, naming its parameter types, and create the new version. CREATE OR REPLACE can't change the signature or return type.
Is SECURITY DEFINER safe?
Yes, if you set search_path in the definition, restrict EXECUTE, and keep the function's job narrow.
Summary
- Functions store reusable logic, in SQL or a procedural language, and can be used in any expression.
- Parameters can have defaults and be passed by name. Functions can return scalars, rows, sets or tables.
- SQL functions with standard bodies are checked at creation, tracked as dependencies, and can be inlined.
- Volatility (
IMMUTABLE,STABLE,VOLATILE) tells the planner what it may assume. Only immutable functions can be indexed.STRICTreturns NULL for NULL input. - Procedures are run with
CALLand can commit and roll back, which suits batch jobs. SECURITY DEFINERfunctions give controlled access. Setsearch_pathand restrictEXECUTE.- Put integrity and data-heavy work in the database, and keep most business workflows in the application.
Practice questions
Write a SQL function products_in(p_category TEXT) that returns the names and prices of the products in a category, cheapest first.
Answer
CREATE FUNCTION products_in(p_category TEXT)
RETURNS TABLE (name TEXT, price NUMERIC)
LANGUAGE sql
STABLE
BEGIN ATOMIC
SELECT p.name, p.price FROM products p
WHERE p.category = p_category
ORDER BY p.price;
END;
SELECT * FROM products_in('lighting');
Which volatility should these functions have: (a) one that converts kilograms to grams, (b) one that looks up a product's price, (c) one that inserts a row into an audit table?
Answer
(a) IMMUTABLE: it depends only on its argument. (b) STABLE: it reads a table, which can change between statements. (c) VOLATILE: it changes data.
Why might a nightly job that deletes millions of old rows be written as a procedure rather than a function?
Answer
A procedure can commit after each batch, so the job doesn't hold one huge transaction with its locks and old row versions for hours, and finished batches survive a failure. A function runs inside a single transaction and can't commit.
What does SET search_path = public, pg_temp protect against in a SECURITY DEFINER function?
Answer
A caller placing their own table or function with the same name earlier in their search path, so that the function, running with its owner's privileges, uses the caller's object instead of the intended one.
Previous: PL/pgSQL Cursors and Error Handling
Next: SQL Triggers

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.