In Development: This textbook is currently
undergoing development and should not be used as an authoritative
source of... well, ANYTHING.
19 Programmability
19.1 Learning Objectives
By the end of this chapter, students will be able to:
- Write a SQL-language function using
CREATE FUNCTIONthat accepts arguments and returns a value. - Write a PL/pgSQL function using procedural constructs including variables, conditionals (
IF/ELSIF/ELSE), and loops. - Classify a function as
IMMUTABLE,STABLE, orVOLATILEand explain how each classification affects query planning and caching. - Call a user-defined function within a
SELECTstatement orWHEREclause. - Write a stored procedure using
CREATE PROCEDUREand invoke it withCALL. - Distinguish between a function and a stored procedure in PostgreSQL, particularly regarding return values and transaction control.
- Implement
COMMITandROLLBACKwithin a stored procedure to manage transactions across multiple statements. - Create a trigger function that returns
NEWorOLDand attach it to a table usingCREATE TRIGGER. - Distinguish between
BEFORE,AFTER, andINSTEAD OFtriggers, and betweenROW-level andSTATEMENT-level triggers. - Design a trigger to enforce a business rule or maintain a derived column that cannot be expressed as a simple constraint.
Stub: User-defined functions (CREATE FUNCTION, PL/pgSQL basics, RETURNS, LANGUAGE, IMMUTABLE/STABLE/VOLATILE, SQL-language functions, using functions in queries), stored procedures (CREATE PROCEDURE, CALL, difference between functions and procedures, transaction control inside procedures, when to use procedures vs functions), and triggers (CREATE TRIGGER, BEFORE/AFTER/INSTEAD OF, ROW vs STATEMENT level, trigger functions, common use cases: audit logs, derived columns, enforcing complex constraints).