DB Triggers-Transactions-etc
DB Triggers-Transactions-etc
● Purpose: They are used to enforce business rules, validate data, and
automate system tasks.
What is a trigger?
Event-Driven: Triggers respond to events like INSERT, UPDATE, DELETE.
Types:
Goal: Log salary changes to an audit table whenever an employee’s salary is updated.
NOTE:
NOTE:
● AFTER UPDATE OF salary: Specifies the event (update on the salary column).
● ON employees: Specifies the table the trigger is associated with.
● FOR EACH ROW: Executes the trigger function for each row affected.
Testing the trigger
-- Initial data
INSERT INTO employees (id, name, salary) VALUES (1, 'Alice', 50000);
-- Update salary
UPDATE employees SET salary = 55000 WHERE id = 1;
Expected Output: A record in salary_audit reflecting the change from 50000 to 55000
Common uses cases for triggers
Enforcing Business Rules: Automatically adjust data or raise errors if rules are
violated.
● Issue:
Transaction A and B could interfere with each other. With Read Committed, A
will see updated balance by B if it re-reads.
Example #2: Inventory Management (Repeatable Read)
● Transaction A: SELECT * FROM inventory WHERE product_id = 123;
● Transaction B: INSERT INTO inventory (product_id, quantity)
VALUES (123, 50); COMMIT;
● Transaction A: The data read remains the same even if new records are
inserted.
ACID Properties in PostgreSQL
● PostgreSQL Default: Read Committed
● Adjusting Isolation Level:
Use SET TRANSACTION ISOLATION LEVEL
Example:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN;
-- Transaction operations go here
COMMIT;