Sobes.tech
Junior — Middle

What are the scenarios for using triggers in database management systems?

sobes.tech AI

Answer from AI

Triggers in DBMS are special procedures that automatically execute upon certain events (insert, update, delete). Main scenarios of use:

  • Automatic data integrity checks and maintenance. For example, automatically deleting related records in another table when a record is deleted.
  • Logging changes. Recording the history of data modifications for audit purposes.
  • Calculating and updating derived values. For example, updating a sum or status field when related data changes.
  • Access restriction and validation. Checking conditions before data modification.

An example of a trigger in PostgreSQL that logs changes in the users table:

CREATE TRIGGER log_user_update
AFTER UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION log_update();

CREATE FUNCTION log_update() RETURNS trigger AS $$
BEGIN
  INSERT INTO user_changes(user_id, changed_at) VALUES (NEW.id, now());
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
What are the scenarios for using triggers in database… - sobes.tech