Sub topic 4
What a SQL Function Returns
A SQL function returns the result of its last SQL statement. This chapter assumes you know basic SELECT statements, PostgreSQL data types, and how to run commands in a PostgreSQL client.
The last statement determines the result
A function can contain several SQL statements, but its declared return type must match the result of the final statement. The final statement is usually a SELECT. A data-modifying statement can also return a value when it uses RETURNING.
CREATE OR REPLACE 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.00The function declares RETURNS numeric, so its final SELECT must produce a numeric value. If the final query produces no row, a scalar SQL function returns NULL. If it produces multiple rows, a scalar function uses the first row. Use a set-returning type when you want every row.
Scalar and composite results
A scalar result is one value, such as an integer, date, or text value. A composite result is one row with several named fields. You can return a table-shaped result with RETURNS TABLE. The names after RETURNS TABLE become output column names and can be used in the final query.
CREATE OR REPLACE FUNCTION order_summary(p_order_id int)
RETURNS TABLE (
order_id int,
total numeric,
status text
)
LANGUAGE sql
AS $$
SELECT o.id, o.total, o.status
FROM orders AS o
WHERE o.id = p_order_id;
$$;
SELECT * FROM order_summary(42);RETURNS TABLE also means the function can return multiple rows. If the query finds no matching orders, the function returns an empty result set, not a row containing NULL values.
A function declared with RETURNS SETOF some_type returns multiple values or rows of that type. You normally call it in the FROM clause:
CREATE OR REPLACE FUNCTION numbers_up_to(p_limit int)
RETURNS SETOF int
LANGUAGE sql
IMMUTABLE
AS $$
SELECT generate_series(1, p_limit);
$$;
SELECT * FROM numbers_up_to(3);This produces three rows: 1, 2, and 3.
Data-changing statements and `RETURNING`
An INSERT, UPDATE, or DELETE can be the final statement when it includes RETURNING. The returned columns become the function result.
CREATE OR REPLACE FUNCTION create_customer(
p_name text,
p_email text
)
RETURNS int
LANGUAGE sql
AS $$
INSERT INTO customers (name, email)
VALUES (p_name, p_email)
RETURNING id;
$$;Here, RETURNING id supplies the integer returned by the function. Without RETURNING, the statement does not provide a value for a non-void return type.
Exercise
What must you change if a function declared RETURNS numeric needs to return every matching price instead of one price?
Show answer
Change it to a set-returning declaration, such as RETURNS SETOF numeric, and call it from the FROM clause.