Stop 13 · Views, Procedures & SecurityTopics · 4/9

User-Defined Functions

Part of the SQL Roadmap

In short

When the same calculation, like adding GST, is copied into twenty queries, one day someone updates nineteen of them. A user-defined function keeps that rule in exactly one place.

A user-defined function returns a value, or a table, and can be used inside queries like a built-in function. Use one when the same calculation, such as a tax rule, appears in many queries.

In a busy dhaba kitchen, the jaadu scoops a spoonful from one big glass jar of reddish spice mix into a row of different bubbling pots.

Think of it like this

The house masala jar

A dhaba in Amritsar doesn't measure out eleven spices for every dish. The owner mixes the house garam masala once, labels the jar, and every cook adds a spoonful. Change the recipe in the jar and every dish changes with it. A function is that jar: one recipe, used anywhere by name.

Watch it happen

price_with_gst(499, 18) in a SELECT

Row from products
Pass inputs
Function body
Return value
Result column

1/5The query reads a product row: Basmati rice, price ₹499.

The big ideas

What you need to know

Returns a value

A scalar function returns one value and can be used in SELECT, WHERE, ORDER BY, anywhere an expression fits.

Or returns a table

A table function RETURNS TABLE (...) and is used in FROM like a view that takes parameters.

Parameters and defaults

Inputs have types and can have default values, so callers can skip the common case.

Label its behaviour

IMMUTABLE means same input, same output, always. STABLE reads tables but doesn't change them. This helps the planner.

See it in code

Walk through the code

sql
1CREATE OR REPLACE FUNCTION price_with_gst(base NUMERIC, gst_rate NUMERIC DEFAULT 18)2RETURNS NUMERIC3LANGUAGE sql4IMMUTABLE5AS $$6  SELECT ROUND(base * (1 + gst_rate / 100), 2);7$$;8 9SELECT product_name,10       price,11       price_with_gst(price)    AS price_18,12       price_with_gst(price, 5) AS price_513FROM products14WHERE category = 'Groceries';15 16-- A table function: a view that takes a parameter17CREATE OR REPLACE FUNCTION orders_in_city(p_city TEXT)18RETURNS TABLE (order_id INT, amount NUMERIC)19LANGUAGE sql20STABLE21AS $$22  SELECT o.order_id, o.amount23  FROM orders o24  JOIN customers c ON c.customer_id = o.customer_id25  WHERE c.city = p_city;26$$;27 28SELECT * FROM orders_in_city('Jaipur') ORDER BY amount DESC;

1/5Name, typed inputs with a default, return type, language and how it behaves.

PostgreSQL syntax; the RETURNS TABLE types must match the real column types. MySQL writes CREATE FUNCTION price_with_gst(base DECIMAL(10,2), rate DECIMAL(5,2)) RETURNS DECIMAL(10,2) DETERMINISTIC RETURN ROUND(base * (1 + rate / 100), 2); with no default values.

Save yourself the pain

Common mistakes

Oops

Marking a function IMMUTABLE when it reads a table or uses now().

Do this instead

Use STABLE for anything that reads data or the clock. Wrong labels can give wrong cached results.

Oops

Wrapping a big lookup query in a function called once per row.

Do this instead

That runs thousands of hidden queries. Use a JOIN instead, and keep scalar functions for simple calculations.

Your mission

Write two functions

~25 min

Quick check

When is a user-defined function a better choice than copying the same expression into many queries?

Go deeper

  1. 1Write a function that calculates the price after GST for an amount.
  2. 2Use it inside a SELECT across a whole table.
  3. 3Learn the difference between a function (returns a value, used in queries) and a procedure (run with CALL).

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge