Language Structure

PL/pgSQL is termed a block-structured language. A block is a sequence of statements between a matched set of DECLARE/BEGIN and END statements. Blocks can be nested—meaning that one block can entirely contain another block, which in turn can contain other blocks, and so on. For example, here is a PL/pgSQL function:

 1 -- 2 -- ch07.sql 3 -- 4 5 CREATE OR REPLACE FUNCTION my_factorial(value INTEGER) RETURNS INTEGER AS $$ 6 DECLARE 7 arg INTEGER; 8 BEGIN 9 10 arg := value; 11 12 IF arg IS NULL OR arg < 0 THEN 13 RAISE NOTICE 'Invalid Number'; 14 RETURN NULL; 15 ELSE 16 IF arg = 1 THEN 17 RETURN 1; 18 ELSE 19 DECLARE 20 next_value INTEGER; 21 BEGIN 22 next_value := my_factorial(arg - 1) * arg; 23 RETURN next_value; 24 END; 25 END ...

Get PostgreSQL, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.