0% found this document useful (0 votes)
3 views24 pages

DB Triggers-Transactions-etc

Uploaded by

Rhea Sanjay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views24 pages

DB Triggers-Transactions-etc

Uploaded by

Rhea Sanjay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

DB Triggers

Understanding Triggers in PostgreSQL

● Definition: Triggers are special functions in an RDBMS that automatically


execute (or "fire") in response to specific events on a particular table or view.

● 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.

Execution: Can execute before or after the event.

Types:

● BEFORE Trigger: Executes before the event.


● AFTER Trigger: Executes after the event.
● INSTEAD OF Trigger: Executes instead of the event (typically used with
views).
Example use case
Scenario: Track changes to employee salaries.

Goal: Log salary changes to an audit table whenever an employee’s salary is updated.

-- Stores employee information -- Stores salary change audit logs


CREATE TABLE employees ( CREATE TABLE salary_audit (
id SERIAL PRIMARY KEY, audit_id SERIAL PRIMARY KEY,
name VARCHAR(100), employee_id INTEGER,
salary NUMERIC old_salary NUMERIC,
); new_salary NUMERIC,
change_date TIMESTAMP
);
Creating a trigger (1/2)
CREATE OR REPLACE FUNCTION log_salary_change ()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO salary_audit (employee_id, old_salary, new_salary, change_date)
VALUES (NEW.id, OLD.salary, NEW.salary, NOW());
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

NOTE:

● NEW: Refers to the new row data.


● OLD: Refers to the old row data.
● RETURN NEW: Returns the new row for INSERT/UPDATE triggers.
Creating a trigger (2/2)
CREATE TRIGGER salary_update_trigger
AFTER UPDATE OF salary
ON employees
FOR EACH ROW
EXECUTE FUNCTION log_salary_change();

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;

-- Check the audit table


SELECT * FROM salary_audit;

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.

Maintaining Audit Trails: Log changes to critical data.

Preventing Invalid Transactions: Cancel operations if certain conditions aren't


met.
Other considerations when using triggers
Performance: Triggers can affect performance, especially if complex.

Debugging: Can be hard to trace trigger-related issues.

Recursive Triggers: Be cautious of triggers that invoke other triggers, potentially


causing infinite loops.
Database functions
● Reusable SQL code that performs a specific task and returns a value.
● Characteristics:
○ Returns a single value or a table
○ Can be used in SQL queries
○ Created with CREATE FUNCTION
○ Written in SQL, PL/pgSQL, or other languages
Example
CREATE OR REPLACE FUNCTION calculate_area(radius NUMERIC)
RETURNS NUMERIC AS $$
BEGIN
RETURN pi() * radius * radius;
END;
$$ LANGUAGE plpgsql;

How to call it:


SELECT calculate_area(5);
Stored procedures
● SQL code units that perform tasks or operations; do not necessarily return a
value.
● Characteristics:
○ Execute a series of SQL statements
○ Can manage transactions (e.g., COMMIT, ROLLBACK)
○ Created with CREATE PROCEDURE
○ Typically written in PL/pgSQL or SQL
Example
CREATE OR REPLACE PROCEDURE add_employee(
emp_name TEXT,
emp_salary NUMERIC
)
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO employees ( name, salary) VALUES (emp_name, emp_salary);
COMMIT ;
END;
$$;

How to call it:


CALL add_employee( 'John Doe' , 60000);
Key differences between the two
● Return Value:
○ Functions return a value.
○ Stored procedures do not necessarily return a value.
● Usage in SQL:
○ Functions can be used directly in SQL queries.
○ Stored procedures are executed with CALL.
● Transaction Control:
○ Stored procedures can manage transactions.
○ Functions typically do not handle transactions.
ACID properties
● Atomicity: All or nothing.
● Consistency: Database remains in a consistent state.
● Isolation: Transactions are isolated from each other.
● Durability: Changes are permanent once committed.
Transaction Isolation Levels
● Read Uncommitted
● Read Committed
● Repeatable Read
● Serializable
Read Uncommitted
● Transactions can read data from other uncommitted transactions.
● Anomalies: Dirty Reads
● Example:
○ Transaction A: UPDATE accounts SET balance = balance - 100 WHERE id = 1;
○ Transaction B: SELECT balance FROM accounts WHERE id = 1;
(Reads data from A before it commits.)
Read Committed
● Description: Transactions can only read committed data.
● Anomalies: Non-repeatable Reads
● Example:
○ Transaction A: SELECT balance FROM accounts WHERE id = 1; (Returns 500)
○ Transaction B: UPDATE accounts SET balance = balance - 100 WHERE id = 1; COMMIT;
○ Transaction A: SELECT balance FROM accounts WHERE id = 1;
(Returns 400 after B commits)
Repeatable Read
● Description: Transactions see a consistent snapshot of the data. No new
changes are visible until the transaction completes.
● Anomalies: Phantom Reads
● Example:
○ Transaction A: SELECT * FROM orders WHERE amount > 100;
○ Transaction B: INSERT INTO orders (amount) VALUES (150); COMMIT;
○ Transaction A: The new row from B is not visible to A, but if it queries again, it may see the
new row.
Serializable
● Description: Transactions are executed in such a way that their results are
equivalent to some serial order of execution.
● Guarantee: No anomalies.
● Example:
○ Transactions are handled as if executed one after another, eliminating all anomalies.
Summary of isolation levels
● Read Uncommitted: Allows Dirty Reads
● Read Committed: Prevents Dirty Reads but allows Non-repeatable Reads
● Repeatable Read: Prevents Dirty Reads and Non-repeatable Reads but
allows Phantom Reads
● Serializable: Prevents all anomalies
Example #1: Bank Transfer (Read Committed)
● Transaction A: Check balance (1000).
● Transaction B: Deduct amount (200) from account (Balance 800).
● Transaction A: Deduct amount (500) from account (Balance 500).

● 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;

You might also like