User-Defined Functions

Updated · 10 min read
mediumPostgreSQL 18sqlfunctionscreate-functionplpgsqlvolatilityinterview

A user-defined function in SQL is a function you write yourself with CREATE FUNCTION, which then works just like built-in functions such as upper() or round(), inside any query. It is used to give a name to a calculation you need again and again, such as "how much does this student still owe on this course?", so every query computes it the same way. In this lesson, we will write functions in plain SQL and in PL/pgSQL, return a single value and a whole table, label functions with their volatility, and compare functions with procedures.

In One Minute

  • CREATE FUNCTION name(params) RETURNS type LANGUAGE sql AS $$ SELECT ... $$ defines a function.
  • Call it inside a query: SELECT name(args), in WHERE, in ORDER BY, anywhere an expression fits.
  • RETURNS TABLE (...) makes a table function, used in FROM.
  • Volatility tells the planner how the result can change: IMMUTABLE, STABLE or VOLATILE (the default).
  • Functions compute and return; procedures perform actions and can commit.

Syntax

SQL
CREATE [OR REPLACE] FUNCTION function_name (param_name data_type [, ...])
RETURNS return_type
LANGUAGE sql | plpgsql
[IMMUTABLE | STABLE | VOLATILE]
AS $$
  -- body
$$;
PartMeans
RETURNS typeThe type of the single value returned
RETURNS TABLE (col type, ...)Returns rows with these columns
LANGUAGE sqlThe body is one or more SQL statements; the last one's result is returned
LANGUAGE plpgsqlThe body is a PL/pgSQL block with variables, IF and RETURN
IMMUTABLE, STABLE, VOLATILEThe volatility label (see below)

A Function That Returns a Value

The amount a student still owes on a course is the course fee minus their payments. As a SQL function:

SQL▶ Try it
CREATE FUNCTION amount_owed(p_student INTEGER, p_course INTEGER)
RETURNS NUMERIC
LANGUAGE sql
STABLE
AS $$
  SELECT c.fee_usd - COALESCE(
           (SELECT sum(p.amount_usd) FROM payments AS p
            WHERE p.student_id = p_student AND p.course_id = p_course), 0)
  FROM courses AS c
  WHERE c.course_id = p_course;
$$;
 
SELECT s.first_name, c.title, amount_owed(e.student_id, e.course_id) AS owed_usd
FROM enrollments AS e
JOIN students AS s ON s.student_id = e.student_id
JOIN courses AS c ON c.course_id = e.course_id
ORDER BY owed_usd DESC, s.first_name, c.title;
Output
CREATE FUNCTION
 
 first_name |       title       | owed_usd
------------+-------------------+----------
 Advitha    | Java Basics       |   450.00
 Advitha    | SQL Basics        |   400.00
 Srihitha   | SQL Basics        |   200.00
 Navika     | JavaScript Basics |     0.00
 Srihitha   | Java Basics       |     0.00
 Srihitha   | Java Collections  |     0.00
 Srihitha   | Java OOP          |     0.00
(7 rows)

Explanation: The function runs once for each enrollment row and returns that enrollment's balance. Advitha hasn't paid yet, so she owes both full fees. Srihitha has paid 200.00 of SQL Basics' 400.00 fee and everything else in full, and Navika has paid both installments of JavaScript Basics. Anyone who needs a balance now calls amount_owed instead of rewriting the subquery.

amount_owed returns each enrollment's remaining balance, computed the same way every time

A PL/pgSQL Function

PL/pgSQL functions add variables, IF and RETURN, for logic that isn't one query:

SQL▶ Try it
CREATE FUNCTION payment_status(p_due DATE, p_paid DATE)
RETURNS TEXT
LANGUAGE plpgsql
IMMUTABLE
AS $$
DECLARE
  days_late INTEGER := p_paid - p_due;
BEGIN
  IF days_late <= 0 THEN
    RETURN 'on time';
  ELSIF days_late <= 3 THEN
    RETURN 'grace period';
  ELSE
    RETURN days_late || ' days late';
  END IF;
END;
$$;
 
SELECT payment_id, due_on, paid_on, payment_status(due_on, paid_on) AS status
FROM payments
ORDER BY payment_id;
Output
CREATE FUNCTION
 
 payment_id |   due_on   |  paid_on   |    status
------------+------------+------------+--------------
          1 | 2025-09-01 | 2025-08-28 | on time
          2 | 2025-11-01 | 2025-10-30 | on time
          3 | 2025-12-01 | 2025-12-03 | grace period
          4 | 2026-01-02 | 2025-12-29 | on time
          5 | 2026-01-05 | 2026-01-05 | on time
          6 | 2025-11-15 | 2025-11-14 | on time
          7 | 2025-12-15 | 2025-12-19 | 4 days late
(7 rows)

Explanation: DECLARE creates a variable and := gives it a value. Subtracting two dates gives a number of days. Payment 3 was two days late, inside the grace period; payment 7 was four days late. Variables, Control Flow and Errors covers PL/pgSQL in more depth.

A Function That Returns a Table

RETURNS TABLE makes a function you query like a table, in the FROM clause:

SQL▶ Try it
CREATE FUNCTION payments_for(p_student INTEGER)
RETURNS TABLE (course TEXT, amount_usd NUMERIC, paid_on DATE)
LANGUAGE sql
STABLE
AS $$
  SELECT c.title, p.amount_usd, p.paid_on
  FROM payments AS p
  JOIN courses AS c ON c.course_id = p.course_id
  WHERE p.student_id = p_student
  ORDER BY p.paid_on;
$$;
 
SELECT * FROM payments_for(103);
Output
CREATE FUNCTION
 
      course       | amount_usd |  paid_on
-------------------+------------+------------
 JavaScript Basics |     225.00 | 2025-11-14
 JavaScript Basics |     225.00 | 2025-12-19
(2 rows)

Explanation: payments_for(103) behaves like a table of Navika's payments with three columns. It can be joined, filtered and sorted like any other table. Table functions are like views that take parameters.

Volatility

Volatility tells PostgreSQL how much a function's result can change, so the planner knows what it may optimize:

LabelPromiseExamples
IMMUTABLESame arguments always give the same result, foreverlower(), payment_status() above
STABLESame result within one statement; may read tablesnow(), amount_owed() above
VOLATILE (default)Can change on every call, or has side effectsrandom(), anything that inserts or updates

PostgreSQL records each function's label, as i, s or v in the catalog, and checks it when you build an index:

SQL▶ Try it
CREATE FUNCTION payment_status(p_due DATE, p_paid DATE)
RETURNS TEXT LANGUAGE sql IMMUTABLE
AS $$ SELECT CASE WHEN p_paid <= p_due THEN 'on time' ELSE 'late' END $$;
 
CREATE FUNCTION course_fee(p_course INTEGER)
RETURNS NUMERIC LANGUAGE plpgsql STABLE
AS $$ BEGIN RETURN (SELECT fee_usd FROM courses WHERE course_id = p_course); END; $$;
 
SELECT DISTINCT proname AS function_name, provolatile AS volatility
FROM pg_proc
WHERE proname IN ('payment_status', 'course_fee', 'now', 'random')
ORDER BY proname;
 
CREATE INDEX payments_fee_idx ON payments (course_fee(course_id));
 
CREATE INDEX payments_status_idx ON payments (payment_status(due_on, paid_on));
Output
CREATE FUNCTION
 
CREATE FUNCTION
 
 function_name  | volatility
----------------+------------
 course_fee     | s
 now            | s
 payment_status | i
 random         | v
(4 rows)
 
ERROR:  functions in index expression must be marked IMMUTABLE
 
CREATE INDEX

Explanation: Our functions sit beside the built-in now() (stable) and random() (volatile). An index stores computed values once, so it accepts only IMMUTABLE functions. course_fee reads a table whose contents can change, so it's rightly STABLE, and PostgreSQL refuses to index it. The index on the immutable payment_status is created.

IMMUTABLE: same forever; STABLE: same within a statement; VOLATILE: may change every call

Functions vs Procedures

FunctionProcedure
Created withCREATE FUNCTIONCREATE PROCEDURE
Run withInside a query: SELECT f(1)On its own: CALL p(1)
ReturnsA value or a tableNothing, or INOUT/OUT parameters
COMMIT / ROLLBACK insideNoYes
Best forCalculations, reusable expressionsActions, multi-step changes, batch jobs

Mixing them up gives a clear error:

SQL▶ Try it
CREATE FUNCTION double_it(n INTEGER) RETURNS INTEGER LANGUAGE sql IMMUTABLE AS $$ SELECT n * 2 $$;
 
CALL double_it(21);
 
SELECT double_it(21) AS doubled;
Output
CREATE FUNCTION
 
ERROR:  double_it(integer) is not a procedure
HINT:  To call a function, use SELECT.
 
 doubled
---------
      42
(1 row)

Explanation: CALL works only for procedures, and the hint says what to do instead. Selecting the function works.

Functions live inside queries and return values; procedures run on their own and perform actions

MySQL uses CREATE FUNCTION ... RETURNS ... DETERMINISTIC and SQL Server distinguishes scalar functions from inline and multi-statement table-valued functions. Tabs showing each database's version are coming to this course.

Common Mistakes

Leaving every function VOLATILE. It's safe, but the planner can't optimize calls, and the function can't be used in an index.

Labeling table-reading functions IMMUTABLE. Results go stale.

Calling a slow function once per row on big tables. A function in SELECT runs for every row; a join or window function may be far faster.

Hiding a function inside WHERE on an indexed column. As Writing Fast Queries showed, WHERE f(col) = x can't use an index on col.

Interview Corner

What's the difference between a scalar function and a table-valued function?

A scalar function returns one value per call and is used in expressions. A table-valued function (RETURNS TABLE in PostgreSQL) returns rows and is used in FROM.

What do IMMUTABLE, STABLE and VOLATILE mean?

They promise how a function's result can change: never for the same inputs, not within one statement, or at any call. The planner uses them to optimize, and only immutable functions can be indexed.

When would you use a function instead of a procedure?

When you need a value inside a query, such as a computed balance in a SELECT. Use a procedure for actions, especially ones that control transactions.

Practice

Challenge: Write an IMMUTABLE SQL function with_tax(p_amount NUMERIC) that adds 8.25% sales tax (Texas's state and local maximum), rounded to cents. Use it to show each course's fee with tax, highest first.

Show solution
SQL▶ Try it
CREATE FUNCTION with_tax(p_amount NUMERIC)
RETURNS NUMERIC
LANGUAGE sql
IMMUTABLE
AS $$
  SELECT round(p_amount * 1.0825, 2);
$$;
 
SELECT title, fee_usd, with_tax(fee_usd) AS fee_with_tax
FROM courses
ORDER BY fee_usd DESC, title;
Output
CREATE FUNCTION
 
       title       | fee_usd | fee_with_tax
-------------------+---------+--------------
 Java Collections  |  550.00 |       595.38
 Java OOP          |  500.00 |       541.25
 Java Basics       |  450.00 |       487.13
 JavaScript Basics |  450.00 |       487.13
 SQL Basics        |  400.00 |       433.00
 Git Basics        |  250.00 |       270.63
(6 rows)

The function depends only on its argument, so IMMUTABLE is correct, and it could even be used in an index.

Quick check: User-defined functions

3 questions
1Where can a scalar function be used?
2A function reads the payments table. Which label fits?
3Why did CREATE INDEX on amount_owed(...) fail?

Key Takeaways

You want toWrite
Return a valueCREATE FUNCTION f(a INTEGER) RETURNS NUMERIC LANGUAGE sql AS $$ SELECT ... $$;
Return rowsRETURNS TABLE (col1 TEXT, col2 NUMERIC)
Use logicLANGUAGE plpgsql AS $$ DECLARE ... BEGIN ... RETURN ...; END; $$
Mark it pureIMMUTABLE
Remove itDROP FUNCTION f(INTEGER);

Was this tutorial helpful?

Lesson 85 of 115