Triggers in SQL

A trigger in SQL is a particular kind of stored procedure that is automatically carried out in reaction to specific occurrences or alterations to the database. These occurrences could involve operations like adding, editing, or removing records from a table. When a trigger is defined on a table, it is connected to one or more of these events, and whenever that event takes place, the trigger's code is run. As a result, developers are able to automate processes or enforce business rules in reaction to modifications to database data.

Triggers can be programmed to run either ahead of or following the linked event. Before triggers can be used to validate data or modify it before it is saved to the database because they run before the related action. After triggers can be used to carry out further processing or update related data because they are triggered after the linked action. The usage of triggers in database programming can be quite effective, but it's important to utilize them wisely. Triggers that are poorly designed may have unforeseen effects, such as sluggish performance or inconsistent data.

In order to enforce business rules or data integrity restrictions, such as making sure that particular fields are not null or that certain values fulfil certain requirements, triggers are frequently utilised. They can also be used to build intricate business logic or to audit data changes. The CREATE TRIGGER statement is used to define triggers, and it includes information on the action to be taken when the trigger fires as well as the table on which the trigger is defined.

In SQL, there are two main types of triggers:

  1. DML Triggers (Data Manipulation Language Triggers): Data manipulation language (DML) events like INSERT, UPDATE, and DELETE statements set off these triggers automatically. Further categorization of DML triggers yields two subtypes:
  • INSTEAD OF Triggers: These triggers substitute another operation that is specified in the trigger for the original DML action. An INSTEAD OF INSERT trigger, for instance, could be used to alter the data that is being inserted before it is actually added to the table.

  • AFTER Triggers: These triggers go into effect after the initial DML procedure is finished. A linked table may be updated or a notification may be generated after the original table has been updated, for instance, using an AFTER UPDATE trigger.

  1. DDL Triggers (Data Definition Language Triggers): Data definition language (DDL) events like CREATE, ALTER, and DROP statements set off these triggers. DDL triggers can be used to audit database schema changes or to enact database-wide policies.

Both DML and DDL triggers can be defined at the database level or at the table level.


DML Triggers are activated in response to changes made to the data in a table, such as inserts, updates, and deletes. There are three types of DML Triggers:

  1. INSERT Triggers: These triggers are activated when a new row is inserted into a table.
  2. UPDATE Triggers: These triggers are activated when a row is updated in a table.
  3. DELETE Triggers: These triggers are activated when a row is deleted from a table.

DDL Triggers, on the other hand, are set off when a database's structure is altered, such as when tables, views, or stored procedures are added to or changed. DDL Triggers are of two different types:

  1. CREATE Triggers: These triggers are activated when a new object, such as a table, view, or stored procedure, is created.
  2. ALTER Triggers: These triggers are activated when an existing object is modified, such as by adding or dropping a column from a table.


Here are some reasons why to use triggers in database:

  1. Data Validation: Prior to being inserted, updated, or deleted from a table, data can be verified using triggers. This can aid in preserving data consistency and integrity.

  2. Auditing: A table's data can be changed, and triggers can be used to track those changes. For troubleshooting or auditing purposes, this can be helpful.

  3. Business Logic: Complex business logic that cannot be implemented using straightforward SQL statements can be implemented using triggers. Use a trigger, for instance, to enforce business rules or to compute a running total.

  4. Data Transformation: Before data is added into, updated into, or removed from a table, it can be transformed using triggers. Use a trigger, for instance, to change the format of data or to do calculations on it.

  5. Synchronization: Data synchronization between two or more tables is possible via triggers. Use a trigger, for instance, to update a related table each time a row is added, changed, or removed from a primary table.

  6. Generating alerts or notifications: When specific conditions are met, triggers can be used to generate alerts or notifications, such as when a significant issue occurs and an email is sent.

In SQL, create triggers using the CREATE TRIGGER statement.

Here is the basic syntax:

CREATE TRIGGER trigger_name {BEFORE | AFTER} {INSERT | UPDATE | DELETE} ON table_name [FOR EACH ROW] BEGIN -- Trigger code goes here END;

Let's break down this syntax:

  • CREATE TRIGGER is the statement used to create a new trigger.
  • trigger_name is the name of the trigger you want to create.
  • {BEFORE | AFTER} specifies when the trigger will be fired, either before or after the triggering event (insert, update, or delete).
  • {INSERT | UPDATE | DELETE} specifies the triggering event that will activate the trigger.
  • ON table_name specifies the table on which the trigger will be created.
  • [FOR EACH ROW] indicates that the trigger will be executed for each row that is affected by the triggering event.
  • BEGIN and END delimit the code block that will be executed when the trigger is fired.

Here is an example of a trigger that updates a column in a table whenever a new row is inserted:

CREATE TRIGGER update_column AFTER INSERT ON my_table FOR EACH ROW BEGIN UPDATE my_table SET column_name = 'new_value' WHERE id = NEW.id; END;


This trigger will activate following the addition of a new row to the my_table table, updating the column_name column with the value "new_value" for the newly added row. The new row that is being inserted is referred to by the term NEW. Perform the following steps in order to build a trigger in SQL:

  1. Define the trigger name: Choose a unique name for your trigger that reflects its purpose.

  2. Specify the triggering event: Choose the event that will activate the trigger, such as an insert, update, or delete operation on a specific table.

  3. Define the trigger scope: Specify whether the trigger will be a row-level or statement-level trigger. A row-level trigger fires once for each row that is affected by the triggering event, while a statement-level trigger fires only once for each triggering event, regardless of the number of rows affected.

  4. Define the trigger timing: Specify whether the trigger will be a before or after trigger. A before trigger fires before the triggering event, while an after trigger fires after the triggering event.

  5. Define the trigger action: Specify the action that the trigger will perform when activated, such as inserting data into another table or updating a field in the current table.

Here's an example of a basic trigger that inserts a new row into a log table whenever a row is deleted from a customer table:

CREATE TRIGGER log_delete_customer AFTER DELETE ON customer FOR EACH ROW INSERT INTO log (event_type, event_time, user_id, table_name, record_id) VALUES ('delete', NOW(), USER(), 'customer', OLD.customer_id);

This after trigger adds a new entry into a log table with details about the deletion event for each row that is deleted from the customer table. It should be noted that the precise syntax for generating a trigger may differ depending on the SQL database system being used; for more information, consult the system's documentation.

Consider a table called "orders" with the following schema:

orders ( order_id INT PRIMARY KEY, order_date DATE, customer_id INT, total_amount DECIMAL(10,2) );

Create a trigger that automatically updates a "customers" table whenever a new order is inserted into the "orders" table. The "customers" table has the following schema:

customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(50), total_orders INT );

The trigger should update the "total_orders" field in the "customers" table for the customer associated with the newly inserted order.

Here's an example of how to create this trigger:

CREATE TRIGGER update_customer_total_orders AFTER INSERT ON orders FOR EACH ROW UPDATE customers SET total_orders = total_orders + 1 WHERE customer_id = NEW.customer_id;

This trigger, which updates the "total_orders" field in the "customers" table for the customer connected to the recently entered order, is an after trigger that activates for each row inserted into the "orders" table.

Comments

Popular posts from this blog

OWASP Top 10

TCP/IP Model

AAA