0% found this document useful (0 votes)
51 views

Trigger Dbms

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Trigger Dbms

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Triggers are procedural code blocks that automatically Syntax of Trigger:

execute in response to specific events occurring in a database.


These events typically include data manipulation operations like CREATE OR REPLACE TRIGGER trigger_name
INSERT, UPDATE, DELETE, or even DDL (Data Definition BEFORE/AFTER DELETE OR INSERT OR UPDATE OF
Language) statements like CREATE, ALTER, or DROP. column_name ON table_name
FOR EACH ROW
DECLARE
Key aspects of triggers: variable_name data_type := initial_value;
1. Event-Based Execution: Triggers are tied to specific events BEGIN
that occur within the database. For instance, a trigger could -- Your PL/SQL instructions go here
activate before or after an INSERT, UPDATE, or DELETE NULL; -- Replace this with your actual logic
operation on a table. END;
2. 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.
3. 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.
4. Event Triggers: Beyond data manipulation, triggers can
respond to database-level events such as login attempts,
schema changes, or system startup/shutdown.
1. CREATE OR REPLACE TRIGGER: This statement creates a new trigger or replaces an existing one with the same name.
2. trigger_name: This is the name you give to your trigger.
3. 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).
4. ON table_name: This specifies the table on which the trigger is being created.
5. FOR EACH ROW: It indicates that the trigger will execute once for each row affected by the triggering statement.
6. DECLARE: This section is where you declare any local variables used within the trigger.
7. 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.
8. BEGIN: Marks the beginning of the block where you write the PL/SQL code for the trigger.
9. 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.
10. 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:

1. Calculate the total price of the items in the order.


2. Update the Total_Price column in the Orders table with the calculated total.
3. 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 1. Trigger Name and Event:
BEFORE INSERT ON Orders calculate_order_total is the trigger name,
FOR EACH ROW firing BEFORE INSERT on the Orders table.
DECLARE 2. FOR EACH ROW: Specifies that the trigger will
order_total NUMBER(10, 2); execute for each row being inserted into the
max_total NUMBER(10, 2) := 1000; -- Example maximum total allowed Orders table.
BEGIN 3. DECLARE: Defines local variables (order_total
-- Calculate the total price of items in the new order and max_total) used within the trigger.
SELECT SUM(item_price * quantity) 4. BEGIN-END: Marks the start and end of the
INTO order_total trigger's PL/SQL block.
FROM Order_Items 5. Logic:
WHERE order_id = :NEW.order_id; • Calculates the order_total by summing
the prices of items related to the new
-- Check if the total exceeds the maximum allowed order.
IF order_total > max_total THEN • Checks if the order_total exceeds the
RAISE_APPLICATION_ERROR(-20001, 'Order total exceeds maximum max_total allowed.
limit.'); • If it exceeds, raises an error; otherwise,
ELSE updates the Total_Price column in the
-- Update the Total_Price column in the Orders table Orders table with the calculated total.
UPDATE Orders
SET Total_Price = order_total
WHERE order_id = :NEW.order_id;
END IF;
END;
Triggers play a vital role in building a robust and reliable database 5. Consistency in Data Operations:
system by providing mechanisms to enforce business rules, They ensure consistency across multiple tables or data elements by
maintain data integrity, enhance security, and streamline data automatically enforcing rules whenever a specific operation occurs
management. Here's how they contribute to a robust database: (like insertion, update, or deletion).

1. Enforcing Business Rules: 6. Implementing Complex Workflows:


Triggers allow you to enforce complex business rules and logic at Triggers can be part of complex workflows, orchestrating multiple
the database level. For instance, ensuring data consistency, steps or actions based on certain conditions, making them useful for
validating input, or executing specific actions based on data managing intricate business processes.
changes. 7. Centralized Logic:
2. Data Validation and Integrity: Having business logic embedded in triggers allows for centralized
They help maintain data integrity by enforcing constraints, ensuring management and enforcement of rules, ensuring consistency across
referential integrity, and validating data before it's inserted, different applications or systems interacting with the database.
updated, or deleted. This prevents inconsistent or invalid data from 8. Reducing Application Logic Complexity:
being stored in the database. By moving certain logic to the database layer, triggers can reduce the
3. Security Measures: complexity of application code, making it simpler and more
Triggers can be used to implement security measures like auditing maintainable.
changes (tracking who, when, and what changes were made), 9. Error Handling and Alerts:
restricting access based on certain conditions, or implementing Triggers can handle errors or exceptional cases, issuing alerts,
security protocols on sensitive data. logging information, or rolling back transactions when necessary,
4. Automated Tasks and Maintenance: ensuring data reliability.
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.
Assertion 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:-
1. Purpose:-
• Assertions are used to enforce specific business rules, integrity constraints, or conditions on the data stored in the
database.
2. 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.
3. 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.
4. 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.
5. 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.
The “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:


1. 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.
2. 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.

You might also like