SQL theory · page 7 of 10

Functions and triggers

PL/pgSQL, volatility, BEFORE and AFTER, and when to use a constraint.

Some logic belongs in the database itself, where every application and report uses it the same way: a function computes a value, a trigger reacts to changes.

Functions

A function has parameters, a return type and a body. A body in SQL is a single query; a body in PL/pgSQL, PostgreSQL's procedural language, adds variables (DECLARE), conditions (IF ... ELSIF ... ELSE ... END IF), loops, and errors (RAISE EXCEPTION). The body is written between $$ marks, so it can contain quotes.

A function can also say how it behaves, which helps the planner: immutable (same inputs, same result, forever: ROUND), stable (the same within one query: CURRENT_DATE) or volatile, the default (may change every call: RANDOM()).

Triggers

A trigger runs a function automatically when rows of a table are inserted, updated or deleted.

ChoiceOptions
WhenBEFORE the change (to check or adjust the row) or AFTER it (to react: log, notify)
How oftenFOR EACH ROW (once per changed row) or FOR EACH statement (once per statement)
Which changeINSERT, UPDATE, UPDATE OF column, DELETE

In a row trigger, NEW is the row as it will be, and OLD the row as it was (in an update or delete). A BEFORE trigger returns NEW to let the row through, a changed NEW to adjust it, or raises an exception to refuse it.

Constraint or trigger?

Prefer a constraint whenever it can express the rule: it is simpler, faster and cannot be forgotten. Use a trigger when the rule needs another table (a claim's loss date inside its policy's period) or must record history (an audit trail of reserve changes).

SELECT trigger_name, event_manipulation, action_timing
FROM information_schema.triggers
WHERE event_object_table = 'claims';
The triggers on claims: none until you create them on Day 7. Try it in the playground
A trigger runs inside the statement that fired it: if it raises an exception, the whole statement is undone.
Practise it on Day 7

Check your understanding

Answer every question, then check.

1. In an update trigger, what is OLD?

2. A rule needs to look at another table to accept a row. Which tool?

3. What does a BEFORE row trigger return to let the row through unchanged?

An unhandled error has occurred. Reload 🗙

Reconnecting…

Your connection to Data Analytics SQL Lab dropped, probably a Wi-Fi blip. Hold on while it reconnects. Your work is kept.

The connection could not be restored. The page will reload in a few seconds.