SQL · Module 13 · Lesson 31 min read

Stored Procedures & DO Blocks

Procedures (PostgreSQL 11+)

SQL
CREATE PROCEDURE archive_old_expenses(p_before DATE)
LANGUAGE plpgsql AS $$
BEGIN
  …
END $$;

CALL archive_old_expenses('2026-10-01');

Function vs procedure

FunctionProcedure
Called withSELECT f() (inside queries)CALL p()
Returns a value✅❌ (only OUT/INOUT parameters)
Can COMMIT/ROLLBACK inside❌✅
Usable in SELECT/WHERE✅❌

When to use a procedure

  • Long batch jobs that should commit in chunks (archive 10 million rows, 10,000 at a time) so one failure doesn't undo hours of work and locks stay short
  • Maintenance tasks: cleanup, recalculating summaries, nightly jobs (with pg_cron)

⚠️ COMMIT inside a procedure only works when it's called directly with CALL (not inside an outer transaction block).

DO blocks – anonymous one-off code

ruby
DO $$
BEGIN
  …PL/pgSQL code…
END $$;
  • Runs immediately, isn't saved, can't take parameters or return values
  • Perfect for one-time scripts and migrations with logic ("add the column only if it doesn't exist"), loops over tables, and data fixes

Scheduling

  • pg_cron extension (available in Supabase): SELECT cron.schedule('nightly-archive', '0 2 * * *', $$CALL archive_old_expenses(current_date - 90)$$);
  • Or an external scheduler calling the database

Good practice

  • Log what the job did (RAISE NOTICE, or insert into a job_runs table)
  • Make jobs idempotent (safe to run twice)
  • Process in batches with LIMIT and commit between batches

Example

SQL
-- Archive table for old expenses
CREATE TABLE expenses_archive (LIKE expenses INCLUDING DEFAULTS);
CREATE TABLE job_runs (job TEXT, rows_moved INT, ran_at TIMESTAMPTZ DEFAULT now());

-- Procedure that moves rows in batches and COMMITs between batches
CREATE PROCEDURE archive_expenses(p_before DATE, p_batch INT DEFAULT 5)
LANGUAGE plpgsql AS $$
DECLARE
  v_moved INT;
  v_total INT := 0;
BEGIN
  LOOP
    WITH batch AS (
      DELETE FROM expenses
      WHERE id IN (SELECT id FROM expenses WHERE spent_on < p_before ORDER BY id LIMIT p_batch)
      RETURNING *
    )
    INSERT INTO expenses_archive OVERRIDING SYSTEM VALUE SELECT * FROM batch;

    GET DIAGNOSTICS v_moved = ROW_COUNT;
    EXIT WHEN v_moved = 0;
    v_total := v_total + v_moved;
    COMMIT;                                   -- each batch is saved on its own
    RAISE NOTICE 'moved % rows (total %)', v_moved, v_total;
  END LOOP;
  INSERT INTO job_runs (job, rows_moved) VALUES ('archive_expenses', v_total);
END $$;

CALL archive_expenses('2026-10-01');
-- NOTICE: moved 5 rows (total 5) … moved 1 rows (total 11)

SELECT (SELECT count(*) FROM expenses) AS active, (SELECT count(*) FROM expenses_archive) AS archived;
-- 20 | 11
SELECT job, rows_moved FROM job_runs;          -- archive_expenses | 11

-- DO block: a migration step that's safe to run twice (idempotent)
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'users' AND column_name = 'phone'
  ) THEN
    ALTER TABLE users ADD COLUMN phone TEXT;
    RAISE NOTICE 'phone column added';
  ELSE
    RAISE NOTICE 'phone column already exists — skipping';
  END IF;
END $$;

-- DO block with a loop: report row counts for several tables
DO $$
DECLARE t TEXT; n BIGINT;
BEGIN
  FOREACH t IN ARRAY ARRAY['users', 'expenses', 'bills'] LOOP
    EXECUTE format('SELECT count(*) FROM %I', t) INTO n;
    RAISE NOTICE '% has % rows', t, n;
  END LOOP;
END $$;

-- Schedule nightly (Supabase / pg_cron):
-- SELECT cron.schedule('archive-nightly', '0 2 * * *', $$CALL archive_expenses(current_date - 90)$$);