Warning: Undefined array key "amp-addthis" in /home/tgagmvup/onlinestudy.guru/wp-content/plugins/addthis/backend/AddThisSharingButtonsFeature.php on line 101
lang="en-US"> Triggers - onlinestudy.guru
Site icon onlinestudy.guru

Triggers

A trigger in a database is a special type of stored procedure that automatically executes (or “fires”) in response to certain events on a particular table or view in the database. Triggers are used to enforce business rules, maintain referential integrity, and automate actions based on database events without requiring explicit invocation by application code.

Key Characteristics of Triggers:

  1. Event-Based Execution: Triggers are associated with specific events such as INSERT, UPDATE, DELETE, or TRUNCATE operations on a table.
  2. Implicit Execution: Triggers are automatically executed when the associated event occurs, making them different from regular stored procedures which are called explicitly.
  3. Timing: Triggers can fire either before the triggering event (BEFORE trigger) or after the triggering event (AFTER trigger).
  4. Access to Data: Triggers have access to both the old values (OLD) and the new values (NEW) of the data affected by the triggering event, allowing them to compare values before and after an operation.
  5. Uses:

Example Scenario:

Suppose you have a Orders table and a Order_Details table. You want to ensure that every time an order detail is inserted, the total amount in the Orders table is updated accordingly. You can achieve this using a trigger:

CREATE OR REPLACE FUNCTION update_order_total()
RETURNS TRIGGER AS $$
BEGIN
    UPDATE Orders
    SET total_amount = (SELECT SUM(unit_price * quantity) FROM Order_Details WHERE order_id = NEW.order_id)
    WHERE order_id = NEW.order_id;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_order_total_trigger
AFTER INSERT OR UPDATE OR DELETE ON Order_Details
FOR EACH ROW
EXECUTE FUNCTION update_order_total();

In this example:

Considerations:

Triggers are powerful tools in database management systems, providing automated enforcement of rules and actions based on defined events, thereby enhancing data integrity and consistency within applications.

Exit mobile version