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

Procedures

Do work, commit inside.

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

A function returns a value. A procedure does a job, like restocking books, and can even commit inside. You run it with call.

  • Functions return
  • Procedures do
  • CALL

A restock procedure

The procedure adds stock to every book below a limit, and reports how many it changed. Call runs it. Run it. Five books restocked, and none are low any more.

query.sqlsql
CREATE PROCEDURE restock(min_stock int, add_qty int) LANGUAGE plpgsql AS $$
DECLARE
  n int;
BEGIN
  UPDATE books SET stock = stock + add_qty WHERE stock < min_stock;
  GET DIAGNOSTICS n = ROW_COUNT;
  RAISE NOTICE 'Restocked % books', n;
END $$;

CALL restock(10, 25);
SELECT count(*) FILTER (WHERE stock < 10) AS still_low FROM books;
Output
CREATE PROCEDURE
NOTICE:  Restocked 5 books
CALL
 still_low
-----------
         0
(1 row)

Function or procedure?

Use a function to calculate and return something, inside a query. Use a procedure for a job with side effects, especially one that commits in batches.

Function

  • Returns a valueUsed in SELECTNo COMMIT inside

Procedure

  • Does a jobRun with CALLCan COMMIT

Summary

Procedures run jobs with call, and can commit inside. Next, triggers.

Key takeaways
  • PROCEDURE
  • CALL
  • COMMIT inside
Next up: Triggers — run code on changes