skip to content

writing functions in SQL

CREATE FUNCTION in plain SQL, IMMUTABLE vs STABLE vs VOLATILE, and when postgres inlines your function.

address
everything.writes.sql_functions
part
part 5, changing data
chapter
chapter 8 of 10
reading time
10 min

a SQL function gives a query or an expression a name and parameters: CREATE FUNCTION ... LANGUAGE sql. a simple one is inlined: the planner pastes its body into your query, so it plans as if you'd typed it out, indexes and all.

volatility is a promise about the function: IMMUTABLE (same input, same output, forever), STABLE (same output within one statement), VOLATILE (anything goes, the default). it decides how often postgres calls it and where it may use it.

the picture

you know how wrapping a bit of logic in a function feels free in most languages? in a database it can cost you an index. a function the planner can't see into is a black box it has to call on every row, and a black box can't be matched against an index.

think of a recipe that says "make the sauce from page 12". a cook who flips to page 12 and reads it can plan the whole meal (start the slow part first, reuse the pan). a cook who's handed a sealed jar labelled "sauce" can only open it when the recipe gets there. inlining is flipping to page 12.

declared as =
is_cheap.sql
  1. 1CREATE FUNCTION is_cheap(p numeric) RETURNS boolean
  2. 2LANGUAGE sql
  3. 3RETURN p < 5;
  4. 4SELECT count(*) FROM order_items WHERE is_cheap(unit_price);
the result for LANGUAGE sql
countint8
858
(1 row)
the plan

inlined: the planner pasted p < 5 into the query, saw unit_price < 5, and used the index.

real output, postgres 18.6 (PGlite 0.5.12) · sql-functions
one tiny function, is_cheap(p) = p < 5, declared five ways, and the plan for the same query around it. the answer is 858 every time. LANGUAGE sql, even marked VOLATILE, is inlined: the plan says unit_price < 5 and uses the index. SECURITY DEFINER, a SET clause or PL/pgSQL make it a black box: a seq scan that calls it on every row.

every block below starts from a fresh copy of the database, so nothing you create sticks.

writing one

the shortest form is an expression after RETURN:

functions.sqldb=shop · session fn
CREATE FUNCTION price_with_tax(p numeric) RETURNS numeric
LANGUAGE sql IMMUTABLE
RETURN round(p * 1.20, 2);
 
SELECT name, price, price_with_tax(price) FROM products WHERE id <= 3 ORDER BY id;
output, from postgres 18.6
#1 · CREATE FUNCTION
#2 · SELECT 3
nametextpricenumericprice_with_taxnumeric
chef's knife49.0058.80
cast iron pan39.5047.40
the art of sql32.0038.40
(3 rows)

a function can return rows too. RETURNS TABLE (...) names the columns, and the body is a whole query:

sqldb=shop · session fn
continues session fn (1 earlier block run first)
CREATE FUNCTION top_customers(n int)
RETURNS TABLE (customer_id int, orders bigint)
LANGUAGE sql STABLE
BEGIN ATOMIC
  SELECT customer_id, count(*) FROM orders
  GROUP BY customer_id
  ORDER BY count(*) DESC, customer_id
  LIMIT n;
END;
 
SELECT * FROM top_customers(n => 3) ORDER BY orders DESC, customer_id;
output, from postgres 18.6
#1 · CREATE FUNCTION
#2 · SELECT 3
customer_idint4ordersint8
157
1336
233
(3 rows)

a set-returning function goes in FROM like a table, and arguments can be passed by name (n => 3) as well as by position. (the outer ORDER BY isn't decoration: the function's rows come back in whatever order its query produced them, and only the outermost ORDER BY is a promise.) BEGIN ATOMIC ... END is a body made of statements; the older way is a string, AS $$ SELECT ... $$. they behave differently in one important way, further down.

inlining

the planner inlines a scalar SQL function when its body is a single expression (a RETURN, or a SELECT with no FROM) and nothing about the function needs to happen at call time. EXPLAIN (VERBOSE) shows what it did:

sqldb=shop
CREATE FUNCTION is_cheap(p numeric) RETURNS boolean LANGUAGE sql RETURN p < 5;
CREATE FUNCTION is_cheap_sd(p numeric) RETURNS boolean LANGUAGE sql SECURITY DEFINER RETURN p < 5;
 
EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM order_items WHERE is_cheap(unit_price);
EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM order_items WHERE is_cheap_sd(unit_price);
output, from postgres 18.6
#1 · CREATE FUNCTION
#2 · CREATE FUNCTION
#3 · EXPLAIN
Aggregate Output: count(*) -> Seq Scan on public.order_items Output: order_id, line_no, product_id, qty, unit_price Filter: (order_items.unit_price < '5'::numeric)
#4 · EXPLAIN
Aggregate Output: count(*) -> Seq Scan on public.order_items Output: order_id, line_no, product_id, qty, unit_price Filter: is_cheap_sd(order_items.unit_price)

the first filter is (order_items.unit_price < '5'::numeric): no function left. the second still says is_cheap_sd(order_items.unit_price). what stops a scalar function from being inlined, from the figure and the manual:

  • SECURITY DEFINER: the body has to run as the owner, so there has to be a call to switch users around.
  • a SET clause (SET search_path = ...): same, a setting changes for the duration of the call.
  • any language but sql: PL/pgSQL is opaque to the planner.
  • a body more volatile than the declaration: declare it IMMUTABLE but call now() inside, and postgres won't inline it (inlining would quietly change what it does).
  • a body that's a real query, with a FROM: that's not a single expression, so a scalar function like that is called, not pasted in.

note what's not on the list: declaring a scalar function VOLATILE. if the body is one harmless expression, it's inlined anyway, as the figure shows. VOLATILE does stop inlining for set-returning functions in FROM, which postgres otherwise inlines as a subquery when they're a single SELECT:

sqldb=shop
CREATE FUNCTION cheap_items(maxp numeric) RETURNS SETOF order_items
LANGUAGE sql STABLE AS $$ SELECT * FROM order_items WHERE unit_price < maxp $$;
CREATE FUNCTION cheap_items_v(maxp numeric) RETURNS SETOF order_items
LANGUAGE sql VOLATILE AS $$ SELECT * FROM order_items WHERE unit_price < maxp $$;
 
EXPLAIN (COSTS OFF) SELECT count(*) FROM cheap_items(5);
EXPLAIN (COSTS OFF) SELECT count(*) FROM cheap_items_v(5);
output, from postgres 18.6
#1 · CREATE FUNCTION
#2 · CREATE FUNCTION
#3 · EXPLAIN
Aggregate -> Seq Scan on order_items Filter: (unit_price < '5'::numeric)
#4 · EXPLAIN
Aggregate -> Function Scan on cheap_items_v

the STABLE one becomes a scan of order_items with the filter in it. the VOLATILE one stays a Function Scan: it runs the whole query on its own and hands back every row, and the outer query can't push anything into it. (a volatile function is supposed to run with its own fresh view of the data, which pasting it into the outer query would break.)

volatility

volatility is a promise you make, and postgres believes it:

promisespostgres mayexamples
IMMUTABLEsame arguments, same result, forever. reads no tablescall it once while planning and keep the result; use it in an indexlower, length, price_with_tax above
STABLEsame arguments, same result within one statementcall it once per scan instead of once per row; use it as an index scan keynow, to_char, anything that reads a table
VOLATILEnothing. may change every call, may writenothing: call it for every row, every timerandom, nextval, anything with side effects
sqldb=shop
SELECT DISTINCT proname, provolatile FROM pg_proc
WHERE proname IN ('lower', 'now', 'to_char', 'random', 'nextval')
ORDER BY provolatile, proname;
output, from postgres 18.6
SELECT 5
pronamenameprovolatilechar
loweri
nows
to_chars
nextvalv
randomv
(5 rows)

(i, s, v. a function you write without saying is v.)

predict the output
sql
-- pick_volatile(x) returns x, and is declared VOLATILE
SELECT name FROM customers WHERE id = pick_volatile(42);
-- customers has 2,000 rows and a primary key on id.
-- how many times is pick_volatile called?
declared =
calls.sql
  1. 1SELECT name FROM customers WHERE id = pick_volatile(42);
  2. 2SELECT nextval('calls') - 1 AS calls;
the result for VOLATILE
callsint8
2000
(1 row)
the plan

VOLATILE: might return something different every time, so it's called for every row. a VOLATILE call can't be an index key: seq scan, function in the filter.

real output, postgres 18.6 (PGlite 0.5.12) · sql-functions
the same function, which returns its argument and counts its own calls, declared three ways. switch and compare the plan and the count. the result is Ada every time.

(these three functions cheat a little to count themselves: bumping a sequence is a side effect, which no STABLE or IMMUTABLE function should have. it's fine for counting, and the reason the next gotcha exists.)

an index can only be built on IMMUTABLE expressions, because its contents must never go stale. to_char on a timestamptz depends on the session's time zone, so it's STABLE, and postgres says no:

sqldb=shop
CREATE INDEX ON customers (to_char(created_at, 'YYYY-MM'));
output, from postgres 18.6
ERROR 42P17: functions in index expression must be marked IMMUTABLE

two kinds of body

a body written as a string (AS $$ ... $$) is stored as text and parsed again when the function is used. a body written as SQL statements (RETURN expr or BEGIN ATOMIC ... END, the SQL-standard form, pg 14+) is parsed once, when you create it, and stored as a tree that points at the actual tables and columns. postgres records those as dependencies.

body =
then =
n_books.sql
  1. 1CREATE FUNCTION n_books() RETURNS bigint LANGUAGE sql
  2. 2AS $$ SELECT count(*) FROM products WHERE category = 'books' $$;
  3. 3ALTER TABLE products RENAME COLUMN category TO kind;
  4. 4SELECT n_books();
ERROR: column "category" does not existSQLSTATE 42703

a string body is stored as text. renaming the column it uses goes through, and the function breaks the next time it's called.

real output, postgres 18.6 (PGlite 0.5.12) · sql-functions
a function that counts books, written both ways. then the column it uses is renamed, or dropped. the string body breaks at the next call. the BEGIN ATOMIC body follows the rename, and refuses to let the column be dropped.

so standard bodies catch a whole class of "renamed a column, broke a function nobody remembered" bugs at migration time instead of at 3 a.m. the string form still has its place: it's the only way to write the body in another language (PL/pgSQL is always a string), and it lets a function mention a table that doesn't exist yet.

one level deeperSECURITY DEFINER and search_path

a SECURITY DEFINER function runs with its owner's privileges, which is how you hand out one specific power (insert into the audit log, read one column of the salaries table) without granting the table. the manual's advice is to always give such a function a fixed SET search_path, so a caller can't put their own table or operator named like yours earlier in the path and have it run with the owner's rights. both of those, as the first figure shows, also mean the function is never inlined. that's usually fine for what SECURITY DEFINER functions do; just don't wrap a hot WHERE clause in one. (schemas, roles and row-level security covers search_path and GRANT.)

keylines

  • a SQL function names an expression or a query. RETURN and BEGIN ATOMIC bodies are parsed once and tracked as dependencies.
  • simple LANGUAGE sql functions are inlined: the planner sees the body, indexes and all.
  • SECURITY DEFINER, SET clauses and other languages make a function a black box.
  • volatility is a promise: IMMUTABLE folds at plan time, STABLE runs once per scan, VOLATILE runs for every row.
  • never claim more than is true: a lying IMMUTABLE gives stale plans and stale indexes.