SlideShare a Scribd company logo
Relational Database Management System
Unit No 4: Triggers
SEMESTER: 2
PREPARED BY:
Definition: A trigger in a Relational Database Management System (RDBMS) is a set of SQL statements that are automatically
executed or fired in response to certain events occurring in a database table. Triggers are typically used to enforce business
rules, validate data integrity, or log changes.
Key Features of Triggers
1.Event-Driven Execution:
• Triggers are activated automatically by predefined events such as INSERT, UPDATE, or DELETE operations on a table.
2.Attached to Tables or Views:
• Triggers are associated with specific tables or views, ensuring that they are invoked whenever changes occur in those
database objects.
3.Predefined Timing:
• Triggers operate based on timing conditions:
• BEFORE: Executes before the triggering event occurs (e.g., before data is inserted).
• AFTER: Executes after the triggering event occurs (e.g., after data is updated).
• INSTEAD OF: Used for views to replace the triggering event.
Triggers in RDBMS
4.Enhances Data Integrity:
• Triggers enforce complex business rules and ensure data consistency by validating or modifying data during
database operations.
5.Automatic Execution:
• Once defined, triggers are executed automatically without explicit invocation by users or applications.
6.Granularity:
• Triggers can be defined at the row-level (executed for each affected row) or statement-level (executed once per
SQL statement).
7.Conditional Execution:
• Triggers can include conditional logic using IF...ELSE statements to control their behavior.
8.Supports Cascading:
• Triggers can initiate other triggers, creating a cascading effect. However, care must be taken to avoid infinite
loops.
9.Access to Old and New Values:
• Triggers can access:
• NEW: Values being inserted or updated.
• OLD: Values being deleted or updated.
10.Security and Audit:
• Triggers can track changes in data, maintain logs, and prevent unauthorized actions, thus enhancing
security and audit capabilities.
11.Customizable Logic:
• Triggers can execute complex procedural logic, such as calling stored procedures or performing
calculations.
• Database-Specific Implementation:
• Trigger syntax and features vary across RDBMS platforms like MySQL, PostgreSQL, SQL Server, and Oracle
• Example of a Trigger
• Use Case: Maintain an audit log of changes in a sales table.
• CREATE TRIGGER log_sales_update
• AFTER UPDATE ON sales
• FOR EACH ROW
• BEGIN
• INSERT INTO sales_audit (sale_id, old_amount, new_amount, update_time)
• VALUES (OLD.sale_id, OLD.amount, NEW.amount, NOW());
• END;
• Event: UPDATE on the sales table.
• Action: Insert a record into the sales_audit table capturing the old and new amounts.
Types of Triggers in RDBMS
• Triggers are powerful tools for automating and enforcing database logic, but they
should be used judiciously to avoid performance bottlenecks or unintended side
effects.
• Triggers can be classified based on timing, events, and scope:
1. Based on Timing
• BEFORE Trigger:
• Executes before the specified event (e.g., BEFORE INSERT, BEFORE UPDATE,
BEFORE DELETE).
• oTypically used for validation or preprocessing before the actual operation.
• AFTER Trigger:
• Executes after the specified event (e.g., AFTER INSERT, AFTER UPDATE, AFTER
DELETE).
• oOften used for logging or maintaining audit trails.
• INSTEAD OF Trigger:
• Used instead of the triggering event (commonly with views).
• Customizes behavior for operations like INSERT, UPDATE, or DELETE on views,
which may not directly support these operations
Based on Scope
• Row-Level Trigger:
• Executes once for each row affected by the event.
• Example: For an UPDATE operation that modifies 10 rows, the trigger fires 10 times.
• Statement-Level Trigger:
• Executes once per SQL statement, regardless of the number of rows affected.
• oExample: For the same UPDATE operation modifying 10 rows, the trigger fires only once.
Trigger Events
• Triggers are activated by specific events on a table or view. The main triggering events
include:
1. INSERT Event
• Triggered when a new record is added to the table.
• oExample Use Case: Automatically populate audit fields such as created_at or created_by.
2. UPDATE Event
• Triggered when an existing record is modified.
• Example Use Case: Maintain a change log to track the old and new values of updated
fields.
3. DELETE Event
• Triggered when a record is deleted from the table.
• Example Use Case: Move the deleted record to an archive table before it is removed.
4. COMBINATION of Events
A single trigger can be defined for multiple events.
• Example: A trigger for INSERT OR UPDATE can handle logic common to both events.
Examples of Trigger Definitions
• BEFORE INSERT Trigger
• Used to validate or modify data before insertion.
• CREATE TRIGGER validate_salary
• BEFORE INSERT ON employees
• FOR EACH ROW
• BEGIN
• IF NEW.salary < 3000 THEN
• SIGNAL SQLSTATE '45000'
• SET MESSAGE_TEXT = 'Salary must be at least 3000';
• END IF;
• END;
AFTER UPDATE Trigger
• Used to log changes after an update operation.
• CREATE TRIGGER log_update
• AFTER UPDATE ON employees
• FOR EACH ROW
• BEGIN
• INSERT INTO audit_log (employee_id, old_salary, new_salary, updated_at)
• VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW());
• END;
INSTEAD OF Trigger (on a view)
• Used to enable updates on views.
• CREATE TRIGGER update_view
• INSTEAD OF UPDATE ON employee_view
• FOR EACH ROW
• BEGIN
• UPDATE employees
• SET name = NEW.name, department = NEW.department
• WHERE id = OLD.id;
• END;
• Triggers are invaluable tools for automating workflows, maintaining data integrity,
and enforcing business rules efficiently.
Creating Triggers in RDBMS
• To create a trigger, you use the CREATE TRIGGER statement, which includes the trigger's name,
timing, event, and body of actions to execute.
• Basic Syntax for Trigger Creation
• CREATE TRIGGER trigger_name
• {BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE}
• ON table_name
• [FOR EACH ROW | FOR EACH STATEMENT]
• BEGIN
• -- Trigger actions (SQL statements)
• END;
Components of Trigger Creation
1. trigger_name:
• A unique name to identify the trigger.
2. Timing (BEFORE, AFTER, or INSTEAD OF):
• o BEFORE: Executes before the specified event.
• o AFTER: Executes after the specified event.
• o INSTEAD OF: Replaces the triggering event (used for views).
3. Event (INSERT, UPDATE, DELETE):
• Specifies the event that activates the trigger.
4. ON table_name:
• The table or view to which the trigger is associated.
5. Scope (FOR EACH ROW or FOR EACH STATEMENT):
• o FOR EACH ROW: Executes once for every row affected.
• o FOR EACH STATEMENT: Executes once for the entire SQL statement.
6. Trigger Body (BEGIN ... END):
• Contains the SQL statements to execute when the trigger fires.
Examples of Trigger Creation
1. BEFORE INSERT Trigger
• Ensures data validation before insertion.
• CREATE TRIGGER validate_age
• BEFORE INSERT ON students
• FOR EACH ROW
• BEGIN
• IF NEW.age < 18 THEN
• SIGNAL SQLSTATE '45000'
• SET MESSAGE_TEXT = 'Age must be 18 or older.';
• END IF;
• END;
2. AFTER UPDATE Trigger
• Logs changes made to a table after an update.
• CREATE TRIGGER log_salary_changes
• AFTER UPDATE ON employees
• FOR EACH ROW
• BEGIN
• INSERT INTO salary_log (employee_id, old_salary, new_salary, change_date)
• VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW());
• END;
3. AFTER DELETE Trigger
• Archives deleted records in a separate table.
• CREATE TRIGGER archive_deleted_customers
• AFTER DELETE ON customers
• FOR EACH ROW
• BEGIN
• INSERT INTO archived_customers (customer_id, name, email, deleted_at)
• VALUES (OLD.customer_id, OLD.name, OLD.email, NOW());
• END;
4. INSTEAD OF Trigger (For Views)
• Handles updates on a view.
• CREATE TRIGGER update_employee_view
• INSTEAD OF UPDATE ON employee_view
• FOR EACH ROW
• BEGIN
• UPDATE employees
• SET name = NEW.name, department_id = NEW.department_id
• WHERE id = OLD.id;
• END;
Best Practices for Creating Triggers
1. Keep Trigger Logic Simple:
• Avoid complex operations that could slow down database performance.
2. Avoid Infinite Loops:
• Ensure that triggers don’t unintentionally activate themselves recursively.
3. Test Thoroughly:
• Test triggers in a non-production environment to ensure proper behavior.
4. Use Naming Conventions:
• Use meaningful names for triggers, such as table_event_action (e.g., employee_before_insert).
5. Monitor Performance:
• Be cautious of triggers that execute for a large number of rows to avoid performance bottlenecks.
• Triggers are powerful tools, but their impact on database performance and behavior requires careful design and
testing.
Implementation of BEFORE and AFTER Triggers
• Triggers are implemented based on when they need to execute relative to an event on a table:
· BEFORE Trigger: Executes before the specified event (e.g., INSERT, UPDATE, DELETE).
· AFTER Trigger: Executes after the specified event.
• Below are detailed implementations for both BEFORE and AFTER triggers.
1. BEFORE Trigger Implementation
Use Case: Validate or modify data before it is written to the table.
• Example: Prevent insertion of a product if its price is less than $1.
• CREATE TRIGGER validate_product_price
• BEFORE INSERT ON products
• FOR EACH ROW
• BEGIN
• IF NEW.price < 1 THEN
• SIGNAL SQLSTATE '45000'
• SET MESSAGE_TEXT = 'Product price must be at least $1';
• END IF;
• END;
• · Trigger Type: BEFORE INSERT
• · Logic: Checks the price column of the new record (NEW.price).
• · Action: Prevents insertion and raises an error if the condition is not met.
2. AFTER Trigger Implementation
• Use Case: Log changes or perform actions after a database event.
• Example: Log all updates to the employees table in an audit_log table.
• CREATE TRIGGER log_employee_updates
• AFTER UPDATE ON employees
• FOR EACH ROW
Aspect BEFORE Trigger AFTER Trigger
Execution Timing Executes before the triggering event. Executes after the triggering event.
Use Case Validate or preprocess data. Log changes or trigger related actions.
Access to Data Can modify NEW values before insertion
or update.
Cannot modify NEW or OLD values; used
for logging or external actions.
Impact
Prevents invalid operations before they
occur.
Reflects changes already committed to
the table.
BEGIN
INSERT INTO audit_log (employee_id, old_salary, new_salary, updated_at)
VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW());
END;
· Trigger Type: AFTER UPDATE
· Logic: Logs changes to the salary field of the employees table.
· Action: Inserts old and new salary values into the audit_log table along with the timestamp.
Combined Example: BEFORE and AFTER Triggers
• Scenario:
1. Validate that the quantity of a product is non-negative before insertion (BEFORE INSERT).
2. Log any product additions into an audit_products table (AFTER INSERT).
• BEFORE INSERT Trigger
• CREATE TRIGGER validate_product_quantity
• BEFORE INSERT ON products
• FOR EACH ROW
• BEGIN
• IF NEW.quantity < 0 THEN
• SIGNAL SQLSTATE '45000'
• SET MESSAGE_TEXT = 'Quantity cannot be negative';
• END IF;
• END;
AFTER INSERT Trigger
• CREATE TRIGGER log_product_inserts
• AFTER INSERT ON products
• FOR EACH ROW
• BEGIN
• INSERT INTO audit_products (product_id, product_name, added_on)
• VALUES (NEW.product_id, NEW.product_name, NOW());
• END;
• Workflow:
o BEFORE INSERT: Ensures no product with a negative quantity is inserted.
o AFTER INSERT: Logs details of successfully added products.
Testing and Execution
• To test the triggers, try running the following queries:
Valid Data:
• INSERT INTO products (product_id, product_name, price, quantity)
• VALUES (1, 'Laptop', 800, 10);
Invalid Data (Triggers Error in BEFORE Trigger):
• INSERT INTO products (product_id, product_name, price, quantity)
• VALUES (2, 'Phone', 500, -5);
• Using BEFORE and AFTER triggers together ensures data integrity while capturing valuable information about database
operations.

More Related Content

PDF
Triggers in PL introduction yo database s
PPT
Database Triggers
PDF
Triggers and active database
PPTX
DBMS: Week 12 - Triggers in MySQL Database Server
PPT
Mca ii-dbms-u-v-transaction management
PPTX
Triggers.PPTX
PPTX
Block Programming - MySQL Triggers - adv topic
PPTX
11 - Trigger mysql advance materi for student.pptx
Triggers in PL introduction yo database s
Database Triggers
Triggers and active database
DBMS: Week 12 - Triggers in MySQL Database Server
Mca ii-dbms-u-v-transaction management
Triggers.PPTX
Block Programming - MySQL Triggers - adv topic
11 - Trigger mysql advance materi for student.pptx

Similar to Basic information of unit-4 form of ppt. (20)

PPT
Trigger
PPTX
MySql Triggers Tutorial - The Webs Academy
PPTX
Multimedia Databases Concepts: Managing images, video, audio and beyond
PPTX
6. triggers
PPT
TRIGGERS IN DATABASE MANAGEMENT SYSTEM.ppt
PPT
Oracle Database Trigger
PDF
triggeroracle-eryk-130621201822-phpapp01.pdf
PDF
Database Automation with MySQL Triggers and Event Schedulers
PPTX
Triggers
PPTX
trigger dbms
PPTX
triggersandactivedatabasesindatabases.pptx
PPTX
Trigger in mysql
PPTX
Unit 4
PPTX
triggers.pptx
PPTX
Sql server ___________session_19(triggers)
PDF
Triggers (1).pdf
PPTX
Triggers
PPT
Intro to trigger and constraint
PPSX
Sql triggers
PDF
Lecture Notes Unit5 chapter16 Trigger Creation
Trigger
MySql Triggers Tutorial - The Webs Academy
Multimedia Databases Concepts: Managing images, video, audio and beyond
6. triggers
TRIGGERS IN DATABASE MANAGEMENT SYSTEM.ppt
Oracle Database Trigger
triggeroracle-eryk-130621201822-phpapp01.pdf
Database Automation with MySQL Triggers and Event Schedulers
Triggers
trigger dbms
triggersandactivedatabasesindatabases.pptx
Trigger in mysql
Unit 4
triggers.pptx
Sql server ___________session_19(triggers)
Triggers (1).pdf
Triggers
Intro to trigger and constraint
Sql triggers
Lecture Notes Unit5 chapter16 Trigger Creation
Ad

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Institutional Correction lecture only . . .
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Insiders guide to clinical Medicine.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Pre independence Education in Inndia.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
master seminar digital applications in india
O5-L3 Freight Transport Ops (International) V1.pdf
Basic Mud Logging Guide for educational purpose
Institutional Correction lecture only . . .
Final Presentation General Medicine 03-08-2024.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
TR - Agricultural Crops Production NC III.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Insiders guide to clinical Medicine.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Pre independence Education in Inndia.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Renaissance Architecture: A Journey from Faith to Humanism
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Supply Chain Operations Speaking Notes -ICLT Program
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O7-L3 Supply Chain Operations - ICLT Program
Ad

Basic information of unit-4 form of ppt.

  • 1. Relational Database Management System Unit No 4: Triggers SEMESTER: 2 PREPARED BY:
  • 2. Definition: A trigger in a Relational Database Management System (RDBMS) is a set of SQL statements that are automatically executed or fired in response to certain events occurring in a database table. Triggers are typically used to enforce business rules, validate data integrity, or log changes. Key Features of Triggers 1.Event-Driven Execution: • Triggers are activated automatically by predefined events such as INSERT, UPDATE, or DELETE operations on a table. 2.Attached to Tables or Views: • Triggers are associated with specific tables or views, ensuring that they are invoked whenever changes occur in those database objects. 3.Predefined Timing: • Triggers operate based on timing conditions: • BEFORE: Executes before the triggering event occurs (e.g., before data is inserted). • AFTER: Executes after the triggering event occurs (e.g., after data is updated). • INSTEAD OF: Used for views to replace the triggering event. Triggers in RDBMS
  • 3. 4.Enhances Data Integrity: • Triggers enforce complex business rules and ensure data consistency by validating or modifying data during database operations. 5.Automatic Execution: • Once defined, triggers are executed automatically without explicit invocation by users or applications. 6.Granularity: • Triggers can be defined at the row-level (executed for each affected row) or statement-level (executed once per SQL statement). 7.Conditional Execution: • Triggers can include conditional logic using IF...ELSE statements to control their behavior. 8.Supports Cascading: • Triggers can initiate other triggers, creating a cascading effect. However, care must be taken to avoid infinite loops. 9.Access to Old and New Values: • Triggers can access: • NEW: Values being inserted or updated. • OLD: Values being deleted or updated.
  • 4. 10.Security and Audit: • Triggers can track changes in data, maintain logs, and prevent unauthorized actions, thus enhancing security and audit capabilities. 11.Customizable Logic: • Triggers can execute complex procedural logic, such as calling stored procedures or performing calculations. • Database-Specific Implementation: • Trigger syntax and features vary across RDBMS platforms like MySQL, PostgreSQL, SQL Server, and Oracle • Example of a Trigger • Use Case: Maintain an audit log of changes in a sales table. • CREATE TRIGGER log_sales_update • AFTER UPDATE ON sales • FOR EACH ROW • BEGIN • INSERT INTO sales_audit (sale_id, old_amount, new_amount, update_time) • VALUES (OLD.sale_id, OLD.amount, NEW.amount, NOW()); • END; • Event: UPDATE on the sales table. • Action: Insert a record into the sales_audit table capturing the old and new amounts.
  • 5. Types of Triggers in RDBMS • Triggers are powerful tools for automating and enforcing database logic, but they should be used judiciously to avoid performance bottlenecks or unintended side effects. • Triggers can be classified based on timing, events, and scope: 1. Based on Timing • BEFORE Trigger: • Executes before the specified event (e.g., BEFORE INSERT, BEFORE UPDATE, BEFORE DELETE). • oTypically used for validation or preprocessing before the actual operation. • AFTER Trigger: • Executes after the specified event (e.g., AFTER INSERT, AFTER UPDATE, AFTER DELETE). • oOften used for logging or maintaining audit trails. • INSTEAD OF Trigger: • Used instead of the triggering event (commonly with views). • Customizes behavior for operations like INSERT, UPDATE, or DELETE on views, which may not directly support these operations
  • 6. Based on Scope • Row-Level Trigger: • Executes once for each row affected by the event. • Example: For an UPDATE operation that modifies 10 rows, the trigger fires 10 times. • Statement-Level Trigger: • Executes once per SQL statement, regardless of the number of rows affected. • oExample: For the same UPDATE operation modifying 10 rows, the trigger fires only once. Trigger Events • Triggers are activated by specific events on a table or view. The main triggering events include: 1. INSERT Event • Triggered when a new record is added to the table. • oExample Use Case: Automatically populate audit fields such as created_at or created_by.
  • 7. 2. UPDATE Event • Triggered when an existing record is modified. • Example Use Case: Maintain a change log to track the old and new values of updated fields. 3. DELETE Event • Triggered when a record is deleted from the table. • Example Use Case: Move the deleted record to an archive table before it is removed. 4. COMBINATION of Events A single trigger can be defined for multiple events. • Example: A trigger for INSERT OR UPDATE can handle logic common to both events. Examples of Trigger Definitions • BEFORE INSERT Trigger • Used to validate or modify data before insertion. • CREATE TRIGGER validate_salary • BEFORE INSERT ON employees • FOR EACH ROW • BEGIN • IF NEW.salary < 3000 THEN • SIGNAL SQLSTATE '45000' • SET MESSAGE_TEXT = 'Salary must be at least 3000'; • END IF; • END;
  • 8. AFTER UPDATE Trigger • Used to log changes after an update operation. • CREATE TRIGGER log_update • AFTER UPDATE ON employees • FOR EACH ROW • BEGIN • INSERT INTO audit_log (employee_id, old_salary, new_salary, updated_at) • VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW()); • END; INSTEAD OF Trigger (on a view) • Used to enable updates on views. • CREATE TRIGGER update_view • INSTEAD OF UPDATE ON employee_view • FOR EACH ROW • BEGIN • UPDATE employees • SET name = NEW.name, department = NEW.department • WHERE id = OLD.id; • END; • Triggers are invaluable tools for automating workflows, maintaining data integrity, and enforcing business rules efficiently.
  • 9. Creating Triggers in RDBMS • To create a trigger, you use the CREATE TRIGGER statement, which includes the trigger's name, timing, event, and body of actions to execute. • Basic Syntax for Trigger Creation • CREATE TRIGGER trigger_name • {BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE} • ON table_name • [FOR EACH ROW | FOR EACH STATEMENT] • BEGIN • -- Trigger actions (SQL statements) • END;
  • 10. Components of Trigger Creation 1. trigger_name: • A unique name to identify the trigger. 2. Timing (BEFORE, AFTER, or INSTEAD OF): • o BEFORE: Executes before the specified event. • o AFTER: Executes after the specified event. • o INSTEAD OF: Replaces the triggering event (used for views). 3. Event (INSERT, UPDATE, DELETE): • Specifies the event that activates the trigger. 4. ON table_name: • The table or view to which the trigger is associated. 5. Scope (FOR EACH ROW or FOR EACH STATEMENT): • o FOR EACH ROW: Executes once for every row affected. • o FOR EACH STATEMENT: Executes once for the entire SQL statement. 6. Trigger Body (BEGIN ... END): • Contains the SQL statements to execute when the trigger fires.
  • 11. Examples of Trigger Creation 1. BEFORE INSERT Trigger • Ensures data validation before insertion. • CREATE TRIGGER validate_age • BEFORE INSERT ON students • FOR EACH ROW • BEGIN • IF NEW.age < 18 THEN • SIGNAL SQLSTATE '45000' • SET MESSAGE_TEXT = 'Age must be 18 or older.'; • END IF; • END; 2. AFTER UPDATE Trigger • Logs changes made to a table after an update. • CREATE TRIGGER log_salary_changes • AFTER UPDATE ON employees • FOR EACH ROW • BEGIN • INSERT INTO salary_log (employee_id, old_salary, new_salary, change_date) • VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW()); • END;
  • 12. 3. AFTER DELETE Trigger • Archives deleted records in a separate table. • CREATE TRIGGER archive_deleted_customers • AFTER DELETE ON customers • FOR EACH ROW • BEGIN • INSERT INTO archived_customers (customer_id, name, email, deleted_at) • VALUES (OLD.customer_id, OLD.name, OLD.email, NOW()); • END; 4. INSTEAD OF Trigger (For Views) • Handles updates on a view. • CREATE TRIGGER update_employee_view • INSTEAD OF UPDATE ON employee_view • FOR EACH ROW • BEGIN • UPDATE employees • SET name = NEW.name, department_id = NEW.department_id • WHERE id = OLD.id; • END;
  • 13. Best Practices for Creating Triggers 1. Keep Trigger Logic Simple: • Avoid complex operations that could slow down database performance. 2. Avoid Infinite Loops: • Ensure that triggers don’t unintentionally activate themselves recursively. 3. Test Thoroughly: • Test triggers in a non-production environment to ensure proper behavior. 4. Use Naming Conventions: • Use meaningful names for triggers, such as table_event_action (e.g., employee_before_insert). 5. Monitor Performance: • Be cautious of triggers that execute for a large number of rows to avoid performance bottlenecks. • Triggers are powerful tools, but their impact on database performance and behavior requires careful design and testing. Implementation of BEFORE and AFTER Triggers • Triggers are implemented based on when they need to execute relative to an event on a table: · BEFORE Trigger: Executes before the specified event (e.g., INSERT, UPDATE, DELETE). · AFTER Trigger: Executes after the specified event. • Below are detailed implementations for both BEFORE and AFTER triggers. 1. BEFORE Trigger Implementation
  • 14. Use Case: Validate or modify data before it is written to the table. • Example: Prevent insertion of a product if its price is less than $1. • CREATE TRIGGER validate_product_price • BEFORE INSERT ON products • FOR EACH ROW • BEGIN • IF NEW.price < 1 THEN • SIGNAL SQLSTATE '45000' • SET MESSAGE_TEXT = 'Product price must be at least $1'; • END IF; • END; • · Trigger Type: BEFORE INSERT • · Logic: Checks the price column of the new record (NEW.price). • · Action: Prevents insertion and raises an error if the condition is not met. 2. AFTER Trigger Implementation • Use Case: Log changes or perform actions after a database event. • Example: Log all updates to the employees table in an audit_log table. • CREATE TRIGGER log_employee_updates • AFTER UPDATE ON employees • FOR EACH ROW
  • 15. Aspect BEFORE Trigger AFTER Trigger Execution Timing Executes before the triggering event. Executes after the triggering event. Use Case Validate or preprocess data. Log changes or trigger related actions. Access to Data Can modify NEW values before insertion or update. Cannot modify NEW or OLD values; used for logging or external actions. Impact Prevents invalid operations before they occur. Reflects changes already committed to the table. BEGIN INSERT INTO audit_log (employee_id, old_salary, new_salary, updated_at) VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW()); END; · Trigger Type: AFTER UPDATE · Logic: Logs changes to the salary field of the employees table. · Action: Inserts old and new salary values into the audit_log table along with the timestamp.
  • 16. Combined Example: BEFORE and AFTER Triggers • Scenario: 1. Validate that the quantity of a product is non-negative before insertion (BEFORE INSERT). 2. Log any product additions into an audit_products table (AFTER INSERT). • BEFORE INSERT Trigger • CREATE TRIGGER validate_product_quantity • BEFORE INSERT ON products • FOR EACH ROW • BEGIN • IF NEW.quantity < 0 THEN • SIGNAL SQLSTATE '45000' • SET MESSAGE_TEXT = 'Quantity cannot be negative'; • END IF; • END;
  • 17. AFTER INSERT Trigger • CREATE TRIGGER log_product_inserts • AFTER INSERT ON products • FOR EACH ROW • BEGIN • INSERT INTO audit_products (product_id, product_name, added_on) • VALUES (NEW.product_id, NEW.product_name, NOW()); • END; • Workflow: o BEFORE INSERT: Ensures no product with a negative quantity is inserted. o AFTER INSERT: Logs details of successfully added products. Testing and Execution • To test the triggers, try running the following queries: Valid Data: • INSERT INTO products (product_id, product_name, price, quantity) • VALUES (1, 'Laptop', 800, 10); Invalid Data (Triggers Error in BEFORE Trigger): • INSERT INTO products (product_id, product_name, price, quantity) • VALUES (2, 'Phone', 500, -5); • Using BEFORE and AFTER triggers together ensures data integrity while capturing valuable information about database operations.