Plpgsql basics: code blocks, variables

plpgsql (programming language pgsql) normally lives in function. But we'll write it outside. You can write the following into pg's shell or into an admin panel's input.

Outside a function, we start writing DO then a string start and a string end.

DO
$do$
...
$do$;

Within the DO we write BEGIN and END. Our sql and plpgsql functions live inside these. Below we will use the raise notice command to output something to the screen.

DO
$do$
BEGIN
  raise notice 'hi there';
END
$do$;

To declare variables we use a DECLARE block before the BEGIN block. Variables are assigned with :=. Strings are surrounded with single quotation marks.

DO
$do$
DECLARE
  name text := 'chris';
BEGIN
  raise notice 'hi %', name;
END
$do$;
postgresql

Edit on github
comments powered by Disqus
Click me