User-Defined Functions (PL/pgSQL / T-SQL) & Control Flow
Write UDFs with control flow while knowing function volatility and side effects.
In plain words
A function is a named little calculation you can reuse inside queries.
Think of it like…
A kitchen's house sauce recipe: written once and used in many dishes. Label it correctly too: if the card says "keeps forever" but it actually goes off in a day, everyone who trusts the label gets a bad result.
Where you’ve seen it
A logistics company computes delivery SLAs in 30 reports with slightly different business-day logic. They replace it with business_days_between(start date, finish date) written in SQL against a holidays table and marked STABLE. Reports now agree, and when a new public holiday is added to the table, every report picks it up.
Words you’ll hear
- SQL vs PL/pgSQL function
- A single SQL statement (often inlined by the planner) vs procedural code with variables and control flow.
- IMMUTABLE / STABLE / VOLATILE
- Same result for the same inputs forever / within one statement / could change at any call.
- RETURNS TABLE / SETOF
- Functions that return rows and can be used in FROM like a table.
- SECURITY DEFINER
- Runs with the owner's privileges; must pin search_path to be safe.
Visual diagram
Theory & example queries
Writing functions and control flow
Prefer LANGUAGE sql for anything expressible as one query: simple SQL functions can be inlined into the calling query, so the planner sees through them and can use indexes. Use PL/pgSQL when you need variables, IF/ELSIF, CASE, loops (FOR r IN SELECT … LOOP), or validation with RAISE EXCEPTION 'invalid plan: %', p_plan. Functions can return a scalar, a composite row, or many rows with RETURNS TABLE (…) / SETOF, which you call in FROM.
Add STRICT when NULL input should give NULL output without running the body, and PARALLEL SAFE when the function doesn't write or depend on session state, so parallel query plans can use it. In SQL Server, scalar T-SQL functions were historically executed row by row and blocked parallelism; SQL Server 2019 added scalar UDF inlining for many cases, and inline table-valued functions have always been planned like views.
| code | price_per_seat |
|---|---|
| starter | 199 |
| pro | 499 |
CREATE FUNCTION plan_price(p_plan text, p_seats int)RETURNS numericLANGUAGE plpgsql STABLEAS $$DECLARE v_price numeric;BEGINSELECT price_per_seat INTO v_priceFROM plansWHERE code = p_plan;IF v_price IS NULL THENRAISE EXCEPTION 'unknown plan: %', p_plan;END IF;RETURN v_price * GREATEST(p_seats, 1);END $$;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Function creation status
Note: Validation runs on invocation. A later unknown plan raises the function exception; creation itself does not evaluate a plan code.
Key takeaway: SQL functions when possible (inlinable); PL/pgSQL for control flow.
Volatility, indexes and security
IMMUTABLE promises the same output for the same input forever: pure maths and string clean-up such as normalize_phone. Only immutable functions can be used in expression indexes (CREATE INDEX ON customers (normalize_phone(phone))). STABLE promises a fixed result within one statement, which suits functions that read tables or depend on the time zone setting. VOLATILE, the default, means anything can change, as with random(), clock_timestamp() or functions that insert rows; the planner calls it for every row and never caches it.
Marking a table-reading function IMMUTABLE so it can be indexed is a well-known trap: the index stores old results, and queries return wrong rows after the table changes. For SECURITY DEFINER functions, which run with the owner's rights, always add SET search_path = pg_catalog, public (or the exact schemas) so a caller can't create a same-named table or function earlier in their path and have your privileged function use it.
CREATE FUNCTION normalize_phone(p text)RETURNS textLANGUAGE sql IMMUTABLE STRICT PARALLEL SAFEAS $$SELECT right(regexp_replace(p, '[^0-9]', '', 'g'), 10) $$;CREATE INDEX customers_phone_norm_idx ON customers (normalize_phone(phone));PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Helper and index creation status
Note: PostgreSQL-style responses; the function must remain deterministic and use only permitted operations for IMMUTABLE indexing.
Key takeaway: Label volatility honestly; pin search_path on SECURITY DEFINER.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Find the repeated logic
Pick an expression or rule copied across queries, such as phone clean-up or business days.
regexp_replace(phone, '[^0-9]', '', 'g') × 30 queries
When to use it & trade-offs
What it is
A user-defined function (UDF) packages logic you can call inside any query: SELECT business_days_between(created_at::date, shipped_at::date) FROM orders. In PostgreSQL you write simple ones in plain SQL and ones with variables and control flow (IF, CASE, loops, RAISE EXCEPTION) in PL/pgSQL; SQL Server uses T-SQL. Every function declares a volatility (IMMUTABLE, STABLE or VOLATILE) that tells the planner whether it can be cached, inlined or used in an index.
Why it matters: Functions remove copy-pasted expressions (normalising phone numbers, fiscal quarters, business days) and make them testable in one place. Written carelessly, they're also a classic cause of slow queries and subtle bugs: a wrongly labelled IMMUTABLE function corrupts index results, row-by-row scalar functions hide a loop, and SECURITY DEFINER functions can be hijacked through search_path.
When to reach for it
- Normalising values used in expression indexes
- Business rules shared by many reports (business days, fiscal periods)
- Set-returning helpers used in FROM
When to avoid or be careful
- IMMUTABLE on functions that read tables or settings
- Scalar functions that run a query for every row of a big result
- SECURITY DEFINER without a fixed search_path
SQL function vs PL/pgSQL function vs application code
Strengths: Can be inlined; usable in indexes when IMMUTABLE.
Watch out: No variables or procedural control flow.
Strengths: Full control flow and error handling.
Watch out: Opaque to the planner; per-row cost if it runs queries inside.
Strengths: Familiar tooling, testing and deployment.
Watch out: Can't be used inside SQL filters, indexes or reports.
Interview signals & numbers to know
When this topic comes up
- “This expression is copied in 30 queries”
- “Can I index on a function?”
- “The query got slow after we wrapped logic in a function”
- Function volatility
- PL/pgSQL
Benchmarks & rules of thumb
- 3
- volatility levels: IMMUTABLE, STABLE, VOLATILE
- VOLATILE
- the default if you don't say
- SQL Server 2019
- scalar UDF inlining
Common mistakes & follow-ups
Common interview mistakes
- Marking a function that looks up exchange rates IMMUTABLE, indexing it, and returning stale results after rates change.
- Calling a PL/pgSQL function that runs SELECT … FROM orders for each of 2 million rows in a report.
- Creating a SECURITY DEFINER function without SET search_path, letting a user substitute their own objects.
Likely interviewer follow-ups
- What's the difference between IMMUTABLE, STABLE and VOLATILE?
- Why can a function make a query slower?
- How would you index a normalised version of a column?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply User-Defined Functions (PL/pgSQL / T-SQL) & Control Flow with hands-on SQL practice and interview Q&A.