Sub topic 1
Your first SQL function
A SQL function in PostgreSQL is a named, reusable piece of SQL stored in the database. You call it from queries the same way you call built-in functions such as lower() or now(). This chapter covers the basic shape of CREATE FUNCTION, how to call the result, and the first decisions you make when you write one. Later chapters go deeper on bodies, parameters, return types, volatility and the planner.
Prerequisites
This chapter assumes you already have the following:
- Basic SELECT, INSERT, UPDATE and DELETE statements.
- Familiarity with PostgreSQL data types such as integer, numeric, text and timestamptz.
- The ability to run statements in psql or another PostgreSQL client.
- A basic understanding of tables, schemas and roles.
You need a role that may create objects in a schema. In a scratch database, your own superuser or database-owner role is enough.
What a SQL function is
PostgreSQL lets you write functions in several languages. LANGUAGE sql is the simplest one. The body is a list of ordinary SQL statements, and the function returns the result of the last one.
SQL functions have no variables, loops or IF statements. You get only what SQL itself offers. This limit is useful. The planner can see through a simple SQL function and often merges its body into the calling query, which makes it cheap to use. Chapter topics on inlining cover this later.
A function is stored in a schema, like a table. Its identity is its name plus its argument types, so add_tax(numeric, numeric) and add_tax(numeric) are different functions. You will see why this matters in the chapter on replacing and overloading.
The shape of CREATE FUNCTION
Here is a complete first function:
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.20)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT price * (1 + rate);
$$;
SELECT add_tax(100);
SELECT add_tax(100, 0.05);The first call returns 120.00. The second returns 105.00. Numeric results keep the scale of the arithmetic, so the trailing zeros are expected.
Each part of the statement has a job:
| Part | Meaning |
|---|---|
| `CREATE FUNCTION add_tax(...)` | Names the function and lists its parameters. |
| `price numeric` | A parameter called `price` of type `numeric`. |
| `rate numeric DEFAULT 0.20` | A parameter with a default, used when the caller omits it. |
| `RETURNS numeric` | The type of the value the function returns. |
| `LANGUAGE sql` | The language of the body. |
| `IMMUTABLE` | A promise about how the function behaves. It is explained below. |
| `AS $$ ... $$` | The body, written as a string literal. |
The clauses after RETURNS (LANGUAGE, IMMUTABLE, AS) can appear in any order. Most people put LANGUAGE first and AS last, as shown here.
The body
The body is a string. The $$ characters are dollar quotes, a way to write a string without escaping the single quotes inside it. The next chapter covers them in detail, along with the newer BEGIN ATOMIC form.
Inside the body, you refer to parameters by name. In add_tax, price and rate are the names given in the parameter list. The body here is one SELECT, and the function returns the value of its single column and single row.
Calling a function
A function call is an expression. You can use it anywhere an expression is allowed:
SELECT add_tax(100) AS gross;
SELECT add_tax(19.99, 0.07) AS gross
WHERE true;You can also use a function in a WHERE clause, an ORDER BY, or an index expression, if the function is marked correctly. That last point is the reason for the IMMUTABLE keyword.
Why IMMUTABLE here
Every function has a volatility category. It tells the planner what the function may do:
VOLATILE(the default): the function may change data, and its result may differ between two calls with the same arguments.STABLE: the function does not change data, and within a single statement it returns the same result for the same arguments.IMMUTABLE: the function does not change data and always returns the same result for the same arguments, forever.
add_tax computes a value only from its arguments, so IMMUTABLE is accurate. If you leave the keyword out, the function becomes VOLATILE. It still works, but the planner then has to assume the worst. For example, you cannot build an index on add_tax(price) unless the function is IMMUTABLE.
A later chapter treats volatility in full. For now, remember the rule: the label is a promise from you to the planner, and PostgreSQL does not check it. If you mark a function IMMUTABLE and it reads a table, queries can return wrong results.
The last statement decides the result
The body can hold several statements separated by semicolons. The function returns the result of the last one. Earlier statements run for their side effects only.
In the simple case, the last statement is a SELECT that produces one column. If it produces more than one row, a function declared RETURNS numeric returns only the first row and discards the rest. If it produces no rows, the function returns NULL.
CREATE FUNCTION first_even(a int, b int)
RETURNS int
LANGUAGE sql
IMMUTABLE
AS $$
SELECT x
FROM (VALUES (a), (b)) AS t(x)
WHERE x % 2 = 0
ORDER BY x;
$$;
SELECT first_even(3, 8);
SELECT first_even(3, 5);The first call returns 8. The second returns NULL, because no row qualified. Because the function is scalar, ORDER BY decides which row counts as "first". Without it, the choice is arbitrary.
The chapter on return values covers composite types and set results.
Checking the function after you create it
Two psql commands help right away:
\df add_taxlists functions with that name, along with their argument and result types.\sf add_taxprints the fullCREATE OR REPLACE FUNCTIONtext that PostgreSQL stored.
You can also query the catalog:
SELECT proname, pg_get_function_arguments(oid) AS args, provolatile
FROM pg_proc
WHERE proname = 'add_tax';The column provolatile holds i for immutable, s for stable and v for volatile.
Common errors
Most first-time failures fall into a few groups.
- A column and a parameter share a name. If a table has a column called
priceand your parameter is also calledprice, the name in the body refers to the column. The column wins in a query that has that table in itsFROMclause. Qualify the parameter with the function name, as inadd_tax.price, or give parameters a prefix such asp_. - The result type does not match the last statement. Declaring
RETURNS integerwhile the last statement returnstextraises an error when you create the function. PostgreSQL checks the last statement against the declared type at creation time. - A missing or misplaced dollar quote. Opening with
$$and closing with$body$leaves the string unterminated. The tags must match exactly. - A statement refers to a table that does not exist yet. For
LANGUAGE sqlwith a string body, PostgreSQL checks the body when you create the function (unlesscheck_function_bodiesis off). The tables a function uses must exist at that time. This is a common problem in migration scripts that create functions before tables. - A wrong volatility label. The function is created without any complaint, and the harm appears later as wrong query results.
Here is the first error in practice:
CREATE TABLE products (id int, price numeric);
CREATE FUNCTION price_of(price numeric)
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT price FROM products WHERE id = 1;
$$;In this body, price is the table column, not the argument, so the function ignores its input. Rename the parameter to p_price, or write price_of.price when you mean the argument.
A simple diagram of what happens
The dotted line shows that a stored function is what a later query finds. Whether inlining happens depends on the function body and its settings, which is the subject of a later chapter.
When to reach for a SQL function
SQL functions suit small, well-defined pieces of logic that you want to name and reuse:
- A calculation repeated across many queries, such as
add_tax. - A lookup that needs a clear name.
- A filter or expression that you want to use in an index.
If you need variables, branching or loops, choose PL/pgSQL. The final chapter of this tutorial gives the decision criteria in detail.
Exercise
Write a SQL function discount(price numeric, pct numeric DEFAULT 10) that returns the price after taking off the given percentage. Decide which volatility label fits, and say what SELECT discount(200) returns.
Show answer
CREATE FUNCTION discount(price numeric, pct numeric DEFAULT 10) RETURNS numeric LANGUAGE sql IMMUTABLE AS $$ SELECT price * (1 - pct / 100); $$; The function uses only its arguments and has no side effects, so IMMUTABLE is accurate. SELECT discount(200) uses the default of 10 and returns 180.00.
Exercise
A table items has a column named qty. You write a function with a parameter also called qty, and the body is SELECT count(*) FROM items WHERE qty > qty;. Why does the function return 0 for any input, and how do you fix it?
Show answer
Inside the query, the unqualified name qty resolves to the column of items, not to the parameter, so the condition compares the column with itself and is never true. Fix it by renaming the parameter (for example p_qty) or by qualifying it with the function name, as in WHERE items.qty > my_function.qty.