NEW and OLD record access in PostgreSQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using triggers in PostgreSQL, we often access the NEW and OLD records to see changes.
We want to understand how the time to access these records grows as the number of rows changes.
Analyze the time complexity of this trigger function snippet.
CREATE FUNCTION trg_update_example() RETURNS trigger AS $$
BEGIN
IF NEW.value IS DISTINCT FROM OLD.value THEN
INSERT INTO audit_log(table_name, old_value, new_value) VALUES (TG_TABLE_NAME, OLD.value, NEW.value);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
This trigger checks if a value changed and logs the old and new values.
In this trigger, the main repeating operation is the trigger firing for each row affected.
- Primary operation: Accessing NEW and OLD records and inserting into audit_log.
- How many times: Once per affected row in the table.
As the number of rows affected increases, the trigger runs once per row.
| Input Size (n rows) | Approx. Operations |
|---|---|
| 10 | 10 trigger executions |
| 100 | 100 trigger executions |
| 1000 | 1000 trigger executions |
Pattern observation: The work grows directly with the number of rows affected.
Time Complexity: O(n)
This means the time to process grows linearly with the number of rows the trigger handles.
[X] Wrong: "Accessing NEW and OLD records is a single operation regardless of rows affected."
[OK] Correct: The trigger runs once per row, so accessing NEW and OLD happens repeatedly, scaling with row count.
Understanding how triggers scale with row count helps you write efficient database logic and shows you grasp how databases handle data changes.
"What if the trigger was defined as FOR EACH STATEMENT instead of FOR EACH ROW? How would the time complexity change?"
Practice
INSERT operation?Solution
Step 1: Understand trigger timing for INSERT
For an INSERT operation, the new row is being added, so the trigger can access the new data using theNEWrecord.Step 2: Identify correct record variable
TheOLDrecord is not available for INSERT because there is no previous row. Therefore,NEWis used to access the inserted row.Final Answer:
NEW -> Option BQuick Check:
INSERT uses NEW = D [OK]
- Using OLD in INSERT triggers
- Confusing NEW and OLD for UPDATE
- Assuming CURRENT or PREVIOUS exist
price inside a DELETE trigger in PostgreSQL?Solution
Step 1: Identify record variable for DELETE
In a DELETE trigger, the row is being removed, so the old data is accessible viaOLD.Step 2: Use correct syntax for column access
PostgreSQL uses dot notation to access columns in record variables, soOLD.priceis correct.Final Answer:
OLD.price -> Option AQuick Check:
DELETE uses OLD.column = A [OK]
- Using NEW in DELETE triggers
- Using arrow (->) instead of dot for record access
- Confusing syntax for JSON operators
IF NEW.quantity < OLD.quantity THEN RAISE NOTICE 'Quantity decreased from % to %', OLD.quantity, NEW.quantity; END IF;
What will be the output if the old quantity was 10 and the new quantity is 7?
Solution
Step 1: Understand the condition in the IF statement
The condition checks if the new quantity is less than the old quantity. Here, 7 < 10 is true.Step 2: Analyze the RAISE NOTICE output
The message prints the old quantity first, then the new quantity, so it will output: 'Quantity decreased from 10 to 7'.Final Answer:
Quantity decreased from 10 to 7 -> Option AQuick Check:
NEW < OLD triggers notice = A [OK]
- Mixing up NEW and OLD values in output
- Assuming no output when condition is true
- Confusing syntax of RAISE NOTICE
CREATE FUNCTION trg_delete_check() RETURNS trigger AS $$
BEGIN
IF NEW.id IS NULL THEN
RAISE EXCEPTION 'ID cannot be null';
END IF;
RETURN OLD;
END;
$$ LANGUAGE plpgsql;What is the error in this function?
Solution
Step 1: Check record variables in DELETE triggers
In DELETE triggers, theNEWrecord is not available because no new row is inserted or updated.Step 2: Identify incorrect usage of NEW
The function incorrectly usesNEW.id, which causes an error. It should useOLD.idinstead.Final Answer:
Using NEW in a DELETE trigger where only OLD is available -> Option CQuick Check:
DELETE triggers have OLD, not NEW = C [OK]
- Using NEW in DELETE triggers
- Returning OLD incorrectly
- Misunderstanding trigger return types
salary column only when the salary is updated to a higher value. Which trigger condition and record access correctly implements this in PostgreSQL?Solution
Step 1: Understand the condition for logging
The trigger should log only when the new salary is greater than the old salary, so the condition isNEW.salary > OLD.salary.Step 2: Use correct record variables for UPDATE
The new salary and id come fromNEWbecause the row is updated with new values.Final Answer:
IF NEW.salary > OLD.salary THEN INSERT INTO log_table VALUES (NEW.id, NEW.salary); END IF; -> Option DQuick Check:
Log when NEW > OLD salary = B [OK]
- Reversing NEW and OLD in condition
- Logging when salary decreases
- Using equality instead of greater than
