Trigger for data validation in PostgreSQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using triggers for data validation in PostgreSQL, it's important to understand how the time to run the trigger changes as the amount of data grows.
We want to know how the trigger's work scales when many rows are inserted or updated.
Analyze the time complexity of the following trigger function and trigger.
CREATE FUNCTION validate_age() RETURNS trigger AS $$
BEGIN
IF NEW.age < 0 OR NEW.age > 120 THEN
RAISE EXCEPTION 'Invalid age: %', NEW.age;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER check_age
BEFORE INSERT OR UPDATE ON persons
FOR EACH ROW EXECUTE FUNCTION validate_age();
This trigger checks that the age column is between 0 and 120 for every inserted or updated row.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The trigger function runs once for each row inserted or updated.
- How many times: It runs exactly as many times as there are rows affected by the operation.
Each row causes the trigger to run once, so the total work grows directly with the number of rows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 trigger executions |
| 100 | 100 trigger executions |
| 1000 | 1000 trigger executions |
Pattern observation: The work increases in a straight line as more rows are processed.
Time Complexity: O(n)
This means the time to validate grows directly with the number of rows inserted or updated.
[X] Wrong: "The trigger runs only once no matter how many rows are changed."
[OK] Correct: In PostgreSQL, row-level triggers run once per row, so the work adds up with each row.
Understanding how triggers scale helps you design efficient database validations and shows you can think about performance in real projects.
"What if we changed the trigger to a statement-level trigger? How would the time complexity change?"
Practice
Solution
Step 1: Understand trigger role
Triggers run automatically when data changes, allowing checks on data.Step 2: Identify validation purpose
Data validation means checking data correctness before saving it.Final Answer:
To automatically check and enforce rules on data before it is saved -> Option CQuick Check:
Trigger = automatic data check [OK]
- Thinking triggers speed up queries
- Confusing triggers with backups
- Assuming triggers create tables
Solution
Step 1: Recall PostgreSQL trigger syntax
PostgreSQL uses EXECUTE FUNCTION for triggers since version 11.Step 2: Identify correct timing and syntax
BEFORE INSERT triggers run before inserting data; syntax must match.Final Answer:
CREATE TRIGGER trg BEFORE INSERT ON table_name EXECUTE FUNCTION func_name(); -> Option DQuick Check:
BEFORE INSERT + EXECUTE FUNCTION = CREATE TRIGGER trg BEFORE INSERT ON table_name EXECUTE FUNCTION func_name(); [OK]
- Using EXECUTE PROCEDURE instead of EXECUTE FUNCTION
- Confusing BEFORE and AFTER timing
- Missing parentheses after function name
CREATE FUNCTION check_price() RETURNS trigger AS $$ BEGIN IF NEW.price < 0 THEN RAISE EXCEPTION 'Price cannot be negative'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql;What happens if you try to insert a row with price = -5?
Solution
Step 1: Analyze trigger function logic
The function checks if NEW.price is less than 0 and raises an exception if true.Step 2: Understand RAISE EXCEPTION effect
RAISE EXCEPTION stops the operation and returns an error to the user.Final Answer:
An error is raised and the insert is stopped -> Option AQuick Check:
Negative price triggers error [OK]
- Assuming data is inserted anyway
- Thinking price auto-corrects
- Ignoring trigger effects
CREATE FUNCTION validate_age() RETURNS trigger AS $$ BEGIN IF NEW.age < 18 THEN RAISE EXCEPTION 'Age must be 18 or older'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql;But when inserting age = 15, no error occurs. What is the likely mistake?
Solution
Step 1: Check function correctness
The function correctly raises exception and returns NEW, syntax is fine.Step 2: Consider trigger attachment
If no error occurs, likely the trigger is not linked to the table to run the function.Final Answer:
The trigger is not attached to the table -> Option BQuick Check:
Trigger must be attached to run function [OK]
- Forgetting to create the trigger after function
- Assuming function runs without trigger
- Misreading RAISE EXCEPTION syntax
Solution
Step 1: Understand validation needs
Email must be non-empty and unique before saving data.Step 2: Choose trigger timing and logic
BEFORE INSERT OR UPDATE trigger can check NEW.email and query table for duplicates, raising exception if invalid.Final Answer:
Create a BEFORE INSERT OR UPDATE trigger that raises exception if NEW.email is empty or exists in the table -> Option AQuick Check:
Validate and check uniqueness before insert/update [OK]
- Relying only on UNIQUE constraint without empty check
- Using AFTER trigger to fix duplicates (too late)
- Setting default instead of raising error
