SQL functions: reusable calculations
Overview
A database function packages a reusable operation behind a name and typed inputs in PostgreSQL. A scalar function returns one value per call; a set-returning function can return several rows. This fixture uses integer cents and nonnegative quantities. PostgreSQL SQL-language functions are defined on the server; SQLite has no SQL CREATE FUNCTION statement and instead supports application-defined callbacks registered on each connection. Run the SQLite snippets through the supplied Python validator, which registers the teaching functions.
First example
SELECT fn_line_total(250,4);Observed SQLite result (rows in JSON):
[ [ 1000 ]]How it works
fn_line_total(price, qty) multiplies two values, returning NULL if either is NULL. The first example calculates a single total; the second applies it to each product. Unlike a scalar function, an aggregate consumes a group. The PostgreSQL definition shown below uses LANGUAGE sql, a dollar-quoted body, and RETURNS bigint. Multiplication is exact within the integer range; real designs need an explicit overflow and rounding policy. CREATE OR REPLACE cannot change an existing signature or return type in place. Prefer a simple expression when abstraction adds no value, and check dependent objects before dropping a function.
Practical example
SELECT id,fn_line_total(price,qty) AS total FROM fn_product ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 300 ], [ 2, 200 ], [ 3, 0 ]]Practice and mistakes
Practice: compute a total for 250 cents and 4 units. Hint 1: call fn_line_total in SELECT. Hint 2: compare with 250*4. Expect 1000. Mistake: assuming every SQL tool has the registered callback; it exists only on a prepared connection.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE FUNCTION fn_line_total(p bigint,q bigint) RETURNS bigintLANGUAGE sql IMMUTABLE STRICT AS $$ SELECT p*q $$;SELECT fn_line_total(250,4);ROLLBACK;Expected result, not executed: [[1000]]