Sub topic 1
Your First SQL Function
Prerequisites
You should know basic SELECT, INSERT, UPDATE, and DELETE statements, recognize common PostgreSQL types such as integer, numeric, and text, and be able to run statements in psql.
Creating a function
A SQL function is a named, reusable SQL expression that you call from queries. This function adds tax to a price, with a default rate:
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); -- 120.00
SELECT add_tax(100, 0.05); -- 105.00Writing the body: dollar quoting and BEGIN ATOMIC
The body is the SQL that runs when the function is called. Dollar quoting, the $$ ... $$ delimiters, lets you write the body without escaping single quotes.
On PostgreSQL 14 and later, BEGIN ATOMIC is an alternative. It parses the body when you create the function, so syntax errors and missing tables appear immediately:
CREATE FUNCTION full_name(first_name text, last_name text)
RETURNS text
LANGUAGE sql
IMMUTABLE STRICT
BEGIN ATOMIC
SELECT first_name || ' ' || last_name;
END;> Note: Use BEGIN ATOMIC only on PostgreSQL 14 or later. Check your version with SELECT version();.
Parameters, defaults and OUT columns
Refer to parameters by name in the body, as add_tax does. Parameters with defaults must come after parameters without defaults.
An OUT parameter names an output column. When you declare one, you can omit RETURNS:
CREATE FUNCTION price_bounds(price numeric, OUT low numeric, OUT high numeric)
LANGUAGE sql
IMMUTABLE
AS $$
SELECT price * 0.9, price * 1.1;
$$;
SELECT * FROM price_bounds(100);What a SQL function returns
A SQL function returns the result of its last statement. The result shape depends on the declaration:
| Declaration | Result |
|---|---|
| `RETURNS numeric` | One value |
| `RETURNS SETOF int` | Many rows, one column |
| `RETURNS TABLE (id int, total numeric)` | Many rows with named columns |
The last statement must produce columns that match the declared return type.
Exercise
Write a function net_price(price numeric, discount numeric) that returns the price after subtracting the discount rate, such as 0.10 for 10 percent off, and call it with net_price(200, 0.1).
Show answer
CREATE FUNCTION netprice(price numeric, discount numeric) RETURNS numeric LANGUAGE sql IMMUTABLE AS $$ SELECT price * (1 - discount); $$; SELECT netprice(200, 0.1); -- returns 180.0