Triggers in database Managementaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

ambermanglani143143 7 views 7 slides Aug 30, 2025
Slide 1
Slide 1 of 7
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7

About This Presentation

A trigger in Database Management System (DBMS) is a special type of stored procedure that is automatically executed or “fired” by the database in response to specific events on a table or view. These events can be INSERT, UPDATE, or DELETE operations. Unlike normal procedures, triggers cannot be...


Slide Content

Triggers are procedural code blocks that automatically execute in response to specific events occurring in a database. These events typically include data manipulation operations like INSERT, UPDATE, DELETE, or even DDL (Data Definition Language) statements like CREATE, ALTER, or DROP . Key aspects of triggers: Event-Based Execution : Triggers are tied to specific events that occur within the database. For instance, a trigger could activate before or after an INSERT, UPDATE, or DELETE operation on a table. Automatic Execution : Triggers execute automatically when their associated events occur. They are part of the database and do not require explicit invocation by a user or application. Business Logic Enforcement : They enforce specific business rules or actions consistently. For example, a trigger can validate data before insertion, maintain data integrity by enforcing constraints, log changes, or propagate changes to other tables. Event Triggers : Beyond data manipulation, triggers can respond to database-level events such as login attempts, schema changes, or system startup/shutdown. Syntax of Trigger: CREATE OR REPLACE TRIGGER trigger_name BEFORE/AFTER DELETE OR INSERT OR UPDATE OF column_name ON table_name FOR EACH ROW DECLARE variable_name data_type := initial_value ; BEGIN -- Your PL/SQL instructions go here NULL; -- Replace this with your actual logic END;

CREATE OR REPLACE TRIGGER : This statement creates a new trigger or replaces an existing one with the same name. trigger_name : This is the name you give to your trigger. BEFORE/AFTER DELETE/INSERT/UPDATE OF column_name : This part specifies when the trigger will fire. It can be before or after a DELETE, INSERT, or UPDATE operation on a specific column ( column_name ) within a table ( table_name ). ON table_name : This specifies the table on which the trigger is being created. FOR EACH ROW : It indicates that the trigger will execute once for each row affected by the triggering statement. DECLARE: This section is where you declare any local variables used within the trigger. variable_name data type := initial_value : Here, you define a variable within the trigger. Replace variable_name , data_type , and initial_value with your specific variable name, data type, and initial value. BEGIN: Marks the beginning of the block where you write the PL/SQL code for the trigger. PL/SQL instructions: This is where you place the logic you want the trigger to execute. It can include conditional statements, data manipulations, or any other PL/SQL statements needed for the trigger's functionality. END: Marks the end of the PL/SQL block. EXAMPLE: Imagine you have a database with tables Orders and Order_Items . Whenever an order is placed (INSERT operation into the Orders table), you want to perform certain actions automatically: Calculate the total price of the items in the order. Update the Total_Price column in the Orders table with the calculated total. Ensure that the order total doesn't exceed a certain limit. Here's how you might create a trigger to handle this scenario:

CREATE OR REPLACE TRIGGER calculate_order_total BEFORE INSERT ON Orders FOR EACH ROW DECLARE order_total NUMBER(10, 2); max_total NUMBER(10, 2) := 1000; -- Example maximum total allowed BEGIN -- Calculate the total price of items in the new order SELECT SUM ( item_price * quantity) INTO order_total FROM Order_Items WHERE order_id = : NEW.order_id ; -- Check if the total exceeds the maximum allowed IF order_total > max_total THEN RAISE_APPLICATION_ERROR (-20001, 'Order total exceeds maximum limit.'); ELSE -- Update the Total_Price column in the Orders table UPDATE Orders SET Total_Price = order_total WHERE order_id = : NEW.order_id ; END IF ; END; Trigger Name and Event : calculate_order_total is the trigger name, firing BEFORE INSERT on the Orders table. FOR EACH ROW: Specifies that the trigger will execute for each row being inserted into the Orders table. DECLARE: Defines local variables ( order_total and max_total ) used within the trigger. BEGIN-END: Marks the start and end of the trigger's PL/SQL block. Logic: Calculates the order_total by summing the prices of items related to the new order. Checks if the order_total exceeds the max_total allowed. If it exceeds, raises an error; otherwise, updates the Total_Price column in the Orders table with the calculated total.

Triggers play a vital role in building a robust and reliable database system by providing mechanisms to enforce business rules, maintain data integrity, enhance security, and streamline data management. Here's how they contribute to a robust database: 1. Enforcing Business Rules: Triggers allow you to enforce complex business rules and logic at the database level. For instance, ensuring data consistency, validating input, or executing specific actions based on data changes. 2. Data Validation and Integrity: They help maintain data integrity by enforcing constraints, ensuring referential integrity, and validating data before it's inserted, updated, or deleted. This prevents inconsistent or invalid data from being stored in the database. 3. Security Measures: Triggers can be used to implement security measures like auditing changes (tracking who, when, and what changes were made), restricting access based on certain conditions, or implementing security protocols on sensitive data. 4. Automated Tasks and Maintenance: Triggers automate routine tasks, reducing the need for manual intervention. They can handle tasks like updating related records, maintaining aggregate values, or performing data clean-up activities. 5. Consistency in Data Operations: They ensure consistency across multiple tables or data elements by automatically enforcing rules whenever a specific operation occurs (like insertion, update, or deletion). 6. Implementing Complex Workflows: Triggers can be part of complex workflows, orchestrating multiple steps or actions based on certain conditions, making them useful for managing intricate business processes. 7. Centralized Logic: Having business logic embedded in triggers allows for centralized management and enforcement of rules, ensuring consistency across different applications or systems interacting with the database. 8. Reducing Application Logic Complexity: By moving certain logic to the database layer, triggers can reduce the complexity of application code, making it simpler and more maintainable. 9. Error Handling and Alerts: Triggers can handle errors or exceptional cases, issuing alerts, logging information, or rolling back transactions when necessary, ensuring data reliability.

A ssertion is a logical condition or predicate that defines a rule or constraint that must hold true for all data in the database. It's a declarative statement that specifies a restriction or condition that the database must always satisfy. Key Points :- Purpose:- Assertions are used to enforce specific business rules, integrity constraints, or conditions on the data stored in the database. Implementation:- Typically written in SQL using the CREATE ASSERTION statement to define the condition. An assertion can reference one or more tables and their columns, specifying a condition that must not be violated. Enforcement: Assertions are checked whenever data is modified (inserted, updated, or deleted) to ensure the defined conditions are met. If the condition defined in the assertion is violated by an operation, the database system prevents the operation from executing, ensuring data consistency and integrity . Usage: Assertions are especially useful when integrity constraints or business rules cannot be fully expressed using other constraints like primary keys, foreign keys, or check constraints. Maintenance: Regular review and modification of assertions might be necessary as business rules evolve or data requirements change over time.

Example: Consider an assertion in an employee database ensuring that the salary of an employee should be within a certain range: CREATE ASSERTION SalaryRangeCheck CHECK (Salary BETWEEN 30000 AND 100000 ); This assertion ensures that any salary inserted or updated in the database falls within the specified range . Assertions complement other integrity constraints in maintaining data accuracy, preventing inconsistencies, and ensuring compliance with business rules. They play a significant role in ensuring data integrity by verifying that the database adheres to specific conditions or rules that aren't easily expressed using traditional constraints.

T he “Division " operation is a fundamental concept used in relational algebra to retrieve specific information based on a particular condition or set of conditions. It's different from typical arithmetic division and involves sets or relations. The division operation is primarily used when dealing with relationships between tables or relations in a relational database. It's commonly used in scenarios where you need to find records that match a certain condition across multiple tables. Let's say you have two relations, R and S, and you want to find all the tuples in R that are associated with all tuples in S. This operation is represented in relational algebra as: R ÷ S To perform the division operation: Attributes: R and S should have a common attribute. For example, if R has attributes A and B, and S has attributes A and C, then A is the common attribute. Result: The result of R ÷ S is a relation containing the attributes of R that are associated with all tuples in S. The division operation in relational algebra is complex and not directly supported in SQL as a separate operator. However, it can be achieved using various SQL constructs like joins, subqueries, and NOT EXISTS or NOT IN clauses.