Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 13 / Topic 4 of 8

SQL functions

A function names a computation and makes it available inside any query. The simplest kind is pure SQL — "an order's total" once, not pasted into forty reports:

CREATE FUNCTION order_total(p_order_id integer)
RETURNS numeric
LANGUAGE sql STABLE
AS $$
  SELECT COALESCE(sum(quantity * unit_price), 0)
  FROM order_items
  WHERE order_id = p_order_id;
$$;
SELECT order_id, order_total(order_id) AS total
FROM orders
ORDER BY order_id
LIMIT 3;
CREATE FUNCTION
 order_id |  total  
----------+---------
        1 | 1270.00
        2 |  799.00
        3 |  135.00
(3 rows)

New pieces: $$ ... $$ is dollar quoting (a string literal that doesn't fight your inner quotes), and STABLE is a volatility promise — this function doesn't change data and returns the same answer within one statement, which lets the planner call it less often. The ladder: IMMUTABLE (the same inputs always give the same output: pure math), STABLE (reads tables but doesn't write), VOLATILE (all bets off: random(), anything writing — the default). Honest labels matter; an IMMUTABLE lie caches wrong answers.

🧪 Quick quiz — answer from memory, then check.

  1. What is $$ for?
  2. IMMUTABLE vs STABLE vs VOLATILE — one phrase each.
Show the answers
  1. Dollar quoting — writing the function body without escaping every quote inside it.
  2. Pure math / reads-but-never-writes (steady within a statement) / may do anything, assume nothing.

Done here? The practice set for Part 13 — 6 exercises with solutions — is on the part page.

Search the guide