Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 149/ 160
08. Transactions, Security & Production SQL Administration

User-Defined Functions (PL/pgSQL / T-SQL) & Control Flow

Write UDFs with control flow while knowing function volatility and side effects.

IntermediatePL/pgSQL · Control Flow3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

A PL/pgSQL function with validationQuery example
1Input dataStart from the source rows or state that the statement sees.
plans
2 rows
plans sample rows
codeprice_per_seat
starter199
pro499
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE FUNCTION plan_price(p_plan text,2  p_seats int)3RETURNS numeric4LANGUAGE plpgsql STABLE5AS $$6DECLARE v_price numeric;7BEGIN8SELECT price_per_seat INTO v_price9FROM plans10WHERE code = p_plan;11IF v_price IS NULL THEN12RAISE EXCEPTION 'unknown plan: %',13  p_plan;14END IF;15RETURN v_price * GREATEST(p_seats, 1);16END $$;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/16
3OutputInspect the representative rows, affected-row count, plan, or command status.
Function creation status
CREATE FUNCTION

Note: Validation runs on invocation. A later unknown plan raises the function exception; creation itself does not evaluate a plan code.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

An immutable helper used in an indexQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE FUNCTION normalize_phone(p text)2RETURNS text3LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE4AS $$5SELECT right(regexp_replace(p,6  '[^0-9]',7  '',8  'g'), 10) $$;910CREATE INDEX customers_phone_norm_idx ON customers (normalize_phone(phone));
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Helper and index creation status
CREATE FUNCTION CREATE INDEX

Note: PostgreSQL-style responses; the function must remain deterministic and use only permitted operations for IMMUTABLE indexing.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Label volatility honestly; pin search_path on SECURITY DEFINER.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Find the repeated logic

Pick an expression or rule copied across queries, such as phone clean-up or business days.

Focus at this step

regexp_replace(phone, '[^0-9]', '', 'g') × 30 queries

What to watch at this step
One
definition
Tip: use ← → to move between steps

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

SQL-language function
Best for: Reusable expressions and single queries

Strengths: Can be inlined; usable in indexes when IMMUTABLE.

Watch out: No variables or procedural control flow.

PL/pgSQL / T-SQL function
Best for: Validation, branching, loops close to the data

Strengths: Full control flow and error handling.

Watch out: Opaque to the planner; per-row cost if it runs queries inside.

Application code
Best for: Logic that changes often or needs external services

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?
Interview tip: Whenever you write a function in an interview, state its volatility and why. It's the detail that shows you know how the planner treats functions.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Multi-Version Concurrency Control (MVCC) & Table Bloat
Next topic
Stored Procedures & Transaction Control Inside Procedures