Skip to main content
Module 12 · Lesson 3 of 447/57 in the course~16 min
Module lessons (3/4)

Introduction to Triggers

Lesson preview5 hands-on exercises readySQL Course · Module 12 — Functions and Triggers

Inspect incoming NEW and outgoing OLD rows with BEFORE and AFTER trigger functions.

What you'll learn in this lesson

  • Write special signed Trigger Functions with no parameters that return RETURNS TRIGGER.
  • Inspect and modify intercepted rows using NEW and OLD contextual records.
  • Block illegal changes from inside the engine by launching RAISE EXCEPTION '...'.

Overview

A Trigger is a reactive rule that fires automatically when a table experiences a INSERT, UPDATE, or DELETE. However, before you can hook it to the table, PostgreSQL requires you to define a special Trigger Function in PL/pgSQL without formal parameters which returns RETURNS TRIGGER.

Each BEFORE or AFTER trigger runs in the same transaction and under the same row-lock as the DML command that activated it: if the trigger launches RAISE EXCEPTION, the entire statement and any changes to it are atomically canceled!

Sections covered in this lesson

  1. 11. Mental Model: What NEW, OLD and RETURN Contain
  2. 22. Progressive & Annotated Examples
  3. 33. Interactive Laboratory: Atomicity and Lock Around Triggers
  4. 44. Diagnostic Verification (Quiz)
  5. 55. Progressive Practical Laboratory
Pro Lesson · Module 12 — Functions and Triggers

Unlock "Introduction to Triggers" and the full SQL Course curriculum

Inspect incoming NEW and outgoing OLD rows with BEFORE and AFTER trigger functions.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in SQL Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.