AI Hints
Home›PostgreSQL Tutorial›Functions and Procedures
PostgreSQL · Lesson 74 of 120

PL/pgSQL

Logic with steps.

⏱ 2 min read▶ Video at 1:06:43🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Some logic needs steps, variables and if statements. PL pg SQL is Postgres's built in programming language, for exactly that.

  • Variables
  • IF / ELSE
  • Loops

A loyalty level

Declare creates a variable. Select into stores the customer's total spending. If, else if and else pick a level. Run it. Three customers, and their loyalty levels.

query.sqlsql
CREATE FUNCTION loyalty(cid int) RETURNS text LANGUAGE plpgsql AS $$
DECLARE
  spent numeric;
BEGIN
  SELECT coalesce(sum(i.quantity * b.price), 0) INTO spent
  FROM orders o JOIN order_items i USING (order_id) JOIN books b USING (book_id)
  WHERE o.customer_id = cid;
  IF spent > 300 THEN RETURN 'gold';
  ELSIF spent > 100 THEN RETURN 'silver';
  ELSE RETURN 'bronze';
  END IF;
END $$;

SELECT customer_id, loyalty(customer_id) FROM customers WHERE customer_id IN (3, 14, 21);
Output
CREATE FUNCTION
 customer_id | loyalty
-------------+---------
           3 | bronze
          14 | silver
          21 | gold
(3 rows)

PL/pgSQL tips

Dollar quoting avoids escaping quotes in the body. Raise notice prints debug messages. Raise exception stops with an error. And keep logic in SQL when you can, since it's usually faster.

keyvalue
$$ ... $$no escaping
RAISE NOTICEdebug
RAISE EXCEPTIONstop with error
Prefer SQLwhen possible

Summary

PL pg SQL adds variables, if statements and loops to the database. Next, procedures.

Key takeaways
  • DECLARE
  • IF / ELSIF
  • RETURN
Next up: Procedures — do work, commit inside