Sunday, December 5, 2010

Introduction

The principal language used within PostgreSQL, other than SQL itself, is PL/pgSQL. This language adds looping and conditionals, as well as exception handling, to PostgreSQL.

This language, handy though it is, doesn't seem to get a lot of discussion on web forums. I may be underestimating the coverage, as it seems many of the PostgreSQL superusers assume it is available, and speak of it as though it were plain old PostgreSQL. However that may be, I hope to be helpful in providing some entry level posts on how to program in PL/pgSQL.  My intention is that these posts will be 'cookbookish', with examples that work, and can be cut-and-pasted and then edited to suit your purposes.  I like to 'work from success', and create custom code by iteratively evolving working code.

PL/pgSQL is for writing functions; you cannot inline PL/pgSQL just anywhere.  That said, you can write a function in PL/pgSQL and call it immediately.  It becomes a permanent element of the database you are connected to, and can be called from other sessions later, until you explicity drop it.

Some presentation conventions:

Code samples will be in block-quotes, like the following example, with syntax highlighting:

DECLARE
    key TEXT;
    delta INTEGER;
BEGIN
    ...
    UPDATE mytab SET val = val + delta 
     WHERE id = key;
END;

SQL and PL/pgSQL language keywords will be in all caps. Table, schema, and column names will be lower case, which is recommended practice to avoid problems due to PostgreSQLs case normalizing.

All examples will have been tested, before posting, using an ordinary account at Rdbhost.com .

You may know PL/pgSQL better than I do, in which case your constructive feedback, via comments, will be welcome.

Edited to add cookbook and 'work from success' items.
Edited to add paragraph on functions

No comments:

Post a Comment