PL/pgSQL
About
It is a powerful SQL scripting language optimized for performance of data intensive tasks, available by default in PostgreSQL, providing:
Control structure;
Variable declaration;
Expressions;
Loops;
Cursors and more.
With it you can create:
Complex functions;
New data types;
Stored procedures and more.
User defined functions CANNOT execute Transactions.
Creating
The structure of a PL/pgSQL function is very similar to a PL/SQL functions seen in Functions.
CREATE FUNCTION function_name(p1 type, p2 type, ...) RETURNS return_type AS
$$
BEGIN
-- statements
END;
$$ LANGUAGE plpgsqlExample
Calling
You can call your functions, by just calling them in queries.
Running without Creating
You can execute blocks without declaring a function with DO.
This way you can test logic without creating a function to later have to delete it.
Usage
Declaring variables
A variable holds a value that can be changed through the block.
Use INTO in queries (right after FROM) to pipe the query results to variables.
When assigning query results to variables, make sure that the return data will fit the variable type being used.
E.g.:
Simple variable can hold 1 col x 1 row.
recordvariables can hold n cols x 1 row.
Overwrite variables names
Use ALIAS FOR to declare a new name for an existing variable.
Copying data types from table columns
Print variable values inside block
Use RAISE NOTICE to print values during execution.
Using IN/OUT without RETURNS
Instead of usign RETURNS to define the return variable you can use IN and OUT to define the parameters that enter and the parameters that returns.
Returning multiple values
Results are returned as columns. (Column ret1 and column ret2)
Subblocks
You can have multiple sub-blocks inside blocks.
For this you must label the outer blocks so that the END keyword can know which block is it ending.
Access outer blocks variables
Access other scope variables by referencing their labels before.
Retuning query results
When returning multiple rows from a function, use SETOF or TABLE in the function definition, and RETURN QUERY in the block.
Must return all the table columns. Use RETURN TABLE to choose columns.
Control structure
if else
case
loop
for loops
Looping from select queries.
foreach
while
continue
Executing other sql commands inside
Use EXECUTE to run some types of SQL queries inside.
Last updated