Alex's Slip-box

These are my org-mode notes in sort of Zettelkasten style

SQL Procedural Language

:ID: B1708529-05EA-41A7-8926-11E93C397DEA

# SQL Procedural Language

It’s a procedural programming language supported by PG. PostgreSQL: Documentation: 12: Chapter¬†42.¬†PL/pgSQL - SQL Procedural Language

# Block Structure

# Basic Example of Block Structure

  • Encapsulated in DO/END
  • Body my be a string literal. That’s what the $$ is for.
  • DECLARE section lets you declare variables, their types and optionally default values
DO $$ 
  counter integer := 0;
  counter := counter + 1;
  RAISE NOTICE 'The current value of counter is %', counter;
END $$;


  • Declare a variable with it’s datatype and optional default value
  • You can copy the datatype from an existing table column from your database. See city_name example below.
  • You can declare constants too, see TAX example below. These can’t be
DO $$ 
  counter    INTEGER := 1;
  first_name VARCHAR(50) := 'John';
  last_name  VARCHAR(50) := 'Doe';
  payment    NUMERIC(11,2) := 20.5;
  city_name := 'San Francisco';
  -- do stuff
END $$;

# Stored Procedure

PostgreSQL Stored Procedures

  • Available in Postgres v11+.
  • When doing Large SQL data migrations with batches, it can be good to commit at each iteration of a loop. We cannot COMMIT transactions in PL/pgSQL unless using a stored procedure or function.