PL/pgSQL — Complete Guide
PL/pgSQL — 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 46 of 100
PL/pgSQL
SQL ✓ → Advanced
Advanced · 2 — Production · ~6 min · PostgreSQL — Functions & Automation
What is this?
PL/pgSQL is PostgreSQL procedural language — variables, IF, loops, exceptions, and SQL embedded in functions and procedures. It compiles to server-side bytecode.
Why should you care?
PostgresVerse loyalty points calculation spans tiers and promos — one plpgsql function keeps logic near data.
See it live — copy this example
Run in pgAdmin or psql.
CREATE OR REPLACE FUNCTION apply_loyalty_points(p_customer_id bigint, p_amount numeric)
RETURNS numeric
LANGUAGE plpgsql
AS $$
DECLARE
pts numeric;
BEGIN
IF p_amount >= 1000 THEN
pts := floor(p_amount / 100) * 2;
ELSE
pts := floor(p_amount / 100);
END IF;
UPDATE customers SET loyalty_points = loyalty_points + pts
WHERE customer_id = p_customer_id;
RETURN pts;
END;
$$;
SELECT apply_loyalty_points(7, 1500);
What happened?
- DECLARE defines pts.
- IF doubles points for orders ≥1000.
- UPDATE adds to customer.
- RETURN sends points back to caller.
Practice next
- Add loyalty_points column to customers.
- Create function and SELECT apply_loyalty_points.
- Wrap body in EXCEPTION WHEN OTHERS for logging pattern.
- Rewrite with CASE instead of IF chain.
- Add STRICT SELECT INTO to error when no row found.
Remember
plpgsql adds control flow to SQL. DECLARE, BEGIN, END structure blocks. Use FOR loop FOR rec IN SELECT for row iteration.
PostgresVerse rewards engine
Checkout calls apply_loyalty_points in same transaction as order insert.
Outcome: Points always match paid amount even if app server crashes mid-request.
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!