Functions — Complete Guide
Functions — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 41 of 100
Functions
SQL ✓ → Advanced
Advanced · 2 — Production · ~6 min · PostgreSQL — Functions & Automation
What is this?
PostgreSQL functions return a value from SQL or PL/pgSQL body — usable in SELECT, WHERE, and constraints. They can be IMMUTABLE, STABLE, or VOLATILE for planner hints.
Why should you care?
PostgresVerse pricing API calls calculate_gst(amount) in SQL so web and batch jobs share one tax rule.
See it live — copy this example
Run in pgAdmin or psql.
CREATE OR REPLACE FUNCTION calculate_gst(amount numeric)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT round(amount * 0.18, 2);
$$;
SELECT product_id, price, calculate_gst(price) AS gst
FROM products;
What happened?
- SQL-language function multiplies price by 18% GST and rounds.
- IMMUTABLE tells planner result depends only on input — safe to index expressions using it.
Practice next
- CREATE FUNCTION in PostgresVerse.
- SELECT gst for several products.
- Try CREATE FUNCTION in pgAdmin and inspect Properties.
- Add function masking email: split_part(email,'@',1) || '@***'.
- Use function in CHECK: CHECK (calculate_gst(price) >= 0).
Remember
Functions encapsulate reusable SQL logic. LANGUAGE sql is simple; plpgsql adds variables and control flow. Volatility category affects optimization.
PostgresVerse GST helper
Finance changes GST rate in one function; invoices and app quotes update together.
Outcome: No hunt for magic number 0.18 across microservices.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!