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.

triangle-exclamation

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 plpgsql

Example

circle-info

Differently from PL/SQL, you return results with RETURN instead of calling a SELECT.

But using SELECT will work.

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.

circle-info

Empty variables are NULL.

circle-exclamation
triangle-exclamation

Overwrite variables names

Use ALIAS FOR to declare a new name for an existing variable.

Copying data types from table columns

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.

circle-info

Blocks have scopes and can have its own variables.

circle-exclamation

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.

circle-exclamation

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