Bird
Raised Fist0
Supabasecloud~10 mins

Row-level triggers for audit logs in Supabase - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Row-level triggers for audit logs
Row Insert/Update/Delete
↓
Trigger fires on row event
↓
Trigger function executes
↓
Audit log entry created
↓
Audit log table updated
↓
End
When a row changes, a trigger runs a function that records details in an audit log table.
Execution Sample
Supabase
CREATE FUNCTION audit_log() RETURNS trigger AS $$
BEGIN
  INSERT INTO audit_logs(table_name, operation, changed_data, changed_at)
  VALUES (TG_TABLE_NAME, TG_OP, row_to_json(COALESCE(NEW, OLD)), now());
  RETURN COALESCE(NEW, OLD);
END;
$$ LANGUAGE plpgsql;
This function logs the table name, operation type, changed row data, and timestamp into audit_logs.
Process Table
StepEventTrigger ActionAudit Log InsertedResult
1Insert row into usersTrigger fires on INSERTInsert audit log with table='users', operation='INSERT', changed_data=NEW row, timestamp=now()Audit log updated with insert event
2Update row in usersTrigger fires on UPDATEInsert audit log with table='users', operation='UPDATE', changed_data=NEW row, timestamp=now()Audit log updated with update event
3Delete row from usersTrigger fires on DELETEInsert audit log with table='users', operation='DELETE', changed_data=OLD row, timestamp=now()Audit log updated with delete event
4No more eventsNo triggerNo audit log insertedEnd of execution
💡 No more row events, trigger stops firing
Status Tracker
VariableStartAfter InsertAfter UpdateAfter DeleteFinal
TG_TABLE_NAMEnullusersusersusersusers
TG_OPnullINSERTUPDATEDELETEDELETE
NEWnull{id:1, name:'Alice'}{id:1, name:'Alice B'}nullnull
OLDnullnull{id:1, name:'Alice'}{id:1, name:'Alice B'}null
Audit Log EntryemptyInserted insert logInserted update logInserted delete log3 entries total
Key Moments - 2 Insights
Why does the trigger use NEW for insert and update but OLD for delete?
Because on insert and update, the new row data is available as NEW, but on delete, the row is gone so OLD holds the deleted row data. See execution_table rows 1-3.
What happens if the trigger function does not return NEW or OLD?
The database expects the trigger to return the row to continue operation. Not returning NEW or OLD can cause errors or prevent the row change. This is why the function returns NEW in the sample.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what operation does the trigger log?
AINSERT
BUPDATE
CDELETE
DSELECT
💡 Hint
Check the 'Trigger Action' and 'Audit Log Inserted' columns at step 2.
At which step does the trigger log the OLD row data?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Audit Log Inserted' column for OLD row usage.
If the trigger function returned NULL instead of NEW, what would happen?
AThe audit log would not be created
BThe trigger would run twice
CThe row change would be canceled
DNothing changes
💡 Hint
Returning NULL in a row-level trigger cancels the operation; see key_moments about return values.
Concept Snapshot
Row-level triggers run on each row change (insert, update, delete).
They call a function that logs details to an audit table.
Use NEW for insert/update data, OLD for delete data.
Always return NEW or OLD to allow the operation.
This helps track who changed what and when.
Full Transcript
Row-level triggers in Supabase run automatically when a row is inserted, updated, or deleted in a table. The trigger calls a function that records the change details into an audit log table. For inserts and updates, the new row data is available as NEW, while for deletes, the old row data is available as OLD. The function inserts a record with the table name, operation type, changed data, and timestamp. It must return NEW or OLD to allow the database operation to complete. This setup helps keep a history of changes for auditing purposes.

Practice

(1/5)
1. What is the main purpose of a row-level trigger in Supabase for audit logs?
easy
A. To automatically record changes made to individual rows in a table
B. To speed up database queries by caching results
C. To create new tables automatically when data is inserted
D. To delete old data from the database periodically

Solution

  1. Step 1: Understand what row-level triggers do

    Row-level triggers activate for each row affected by an insert, update, or delete operation.
  2. Step 2: Connect triggers to audit logs

    They are used to record changes to rows, capturing who changed what and when.
  3. Final Answer:

    To automatically record changes made to individual rows in a table -> Option A
  4. Quick Check:

    Row-level trigger purpose = record row changes [OK]
Hint: Triggers log row changes automatically for audit [OK]
Common Mistakes:
  • Thinking triggers speed up queries
  • Confusing triggers with table creation
  • Assuming triggers delete old data
2. Which of the following is the correct syntax to create a row-level trigger in Supabase that fires AFTER an UPDATE on a table named users?
easy
A. CREATE TRIGGER user_update AFTER INSERT ON users FOR EACH ROW EXECUTE FUNCTION audit_log();
B. CREATE TRIGGER user_update BEFORE UPDATE ON users FOR EACH STATEMENT EXECUTE FUNCTION audit_log();
C. CREATE TRIGGER user_update AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION audit_log();
D. CREATE TRIGGER user_update AFTER UPDATE ON users FOR EACH STATEMENT EXECUTE FUNCTION audit_log();

Solution

  1. Step 1: Identify trigger timing and event

    The question asks for AFTER UPDATE trigger on table users.
  2. Step 2: Confirm row-level execution

    Row-level triggers use FOR EACH ROW, not FOR EACH STATEMENT.
  3. Final Answer:

    CREATE TRIGGER user_update AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION audit_log(); -> Option C
  4. Quick Check:

    AFTER UPDATE + FOR EACH ROW = CREATE TRIGGER user_update AFTER UPDATE ON users FOR EACH ROW EXECUTE FUNCTION audit_log(); [OK]
Hint: Use AFTER UPDATE and FOR EACH ROW for row-level update triggers [OK]
Common Mistakes:
  • Using BEFORE instead of AFTER
  • Using FOR EACH STATEMENT instead of FOR EACH ROW
  • Using INSERT event instead of UPDATE
3. Given this trigger function snippet in Supabase SQL:
CREATE OR REPLACE FUNCTION audit_log() RETURNS trigger AS $$
BEGIN
  INSERT INTO audit_table(user_id, action, changed_at)
  VALUES (NEW.id, TG_OP, NOW());
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

What will happen when a row in the users table is updated?
medium
A. A new row is inserted into audit_table with the user's id, action type, and timestamp
B. The updated row in users is deleted
C. The trigger function will cause a syntax error and fail
D. Nothing happens because OLD is not used

Solution

  1. Step 1: Analyze the trigger function logic

    The function inserts a row into audit_table with NEW.id, operation type TG_OP, and current time.
  2. Step 2: Understand trigger behavior on update

    On update, NEW holds the new row data, so the insert logs the change.
  3. Final Answer:

    A new row is inserted into audit_table with the user's id, action type, and timestamp -> Option A
  4. Quick Check:

    Trigger inserts audit record on update = A new row is inserted into audit_table with the user's id, action type, and timestamp [OK]
Hint: Trigger inserts audit row using NEW and TG_OP on update [OK]
Common Mistakes:
  • Thinking OLD is required for insert
  • Assuming trigger deletes rows
  • Confusing syntax causing errors
4. You wrote this trigger function to log deletes:
CREATE OR REPLACE FUNCTION audit_log_delete() RETURNS trigger AS $$
BEGIN
  INSERT INTO audit_table(user_id, action, changed_at)
  VALUES (NEW.id, TG_OP, NOW());
  RETURN OLD;
END;
$$ LANGUAGE plpgsql;

But it fails when deleting rows. What is the error?
medium
A. TG_OP cannot be used in trigger functions
B. RETURN OLD is invalid in DELETE triggers
C. NOW() is not allowed in trigger functions
D. Using NEW.id on DELETE triggers causes an error because NEW is NULL

Solution

  1. Step 1: Understand DELETE trigger context

    On DELETE, NEW is NULL because the row is removed; OLD holds the deleted row.
  2. Step 2: Identify the error in the function

    The function uses NEW.id which is NULL on DELETE, causing failure.
  3. Final Answer:

    Using NEW.id on DELETE triggers causes an error because NEW is NULL -> Option D
  4. Quick Check:

    DELETE triggers use OLD, not NEW [OK]
Hint: Use OLD, not NEW, in DELETE triggers to avoid errors [OK]
Common Mistakes:
  • Using NEW in DELETE triggers
  • Thinking RETURN OLD is invalid
  • Believing TG_OP or NOW() cause errors
5. You want to create an audit log that records who updated a row in the orders table, including old and new values. Which approach correctly combines row-level triggers and audit logging in Supabase?
hard
A. Create a trigger function that only logs NEW data and create a BEFORE INSERT trigger on orders
B. Create a trigger function that inserts into audit_orders using both OLD and NEW row data, then create AFTER UPDATE trigger FOR EACH ROW on orders
C. Create a trigger function that deletes old rows from orders and logs the deletion
D. Create a trigger function that logs changes only when rows are inserted, ignoring updates

Solution

  1. Step 1: Identify audit log needs

    You want to log who updated rows and capture old and new values for changes.
  2. Step 2: Choose correct trigger timing and data

    Use AFTER UPDATE trigger FOR EACH ROW to access OLD and NEW data and insert audit record.
  3. Step 3: Confirm audit table insert logic

    The trigger function should insert both OLD and NEW values into audit_orders for full change history.
  4. Final Answer:

    Create a trigger function that inserts into audit_orders using both OLD and NEW row data, then create AFTER UPDATE trigger FOR EACH ROW on orders -> Option B
  5. Quick Check:

    Use AFTER UPDATE + OLD/NEW + FOR EACH ROW for full audit [OK]
Hint: Use AFTER UPDATE trigger with OLD and NEW for full audit logs [OK]
Common Mistakes:
  • Logging only NEW data misses old values
  • Using BEFORE INSERT triggers for updates
  • Deleting rows instead of logging changes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard