Bird
Raised Fist0
PostgreSQLquery~10 mins

Trigger for data validation in PostgreSQL - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Trigger for data validation
Insert/Update/Delete operation
Trigger fires BEFORE/AFTER operation
Trigger function runs
Validation passes
Operation allowed
End
When a data change happens, the trigger runs a function that checks the data. If the data is valid, the change continues; if not, it stops with an error.
Execution Sample
PostgreSQL
CREATE FUNCTION validate_age() RETURNS trigger AS $$
BEGIN
  IF NEW.age < 0 THEN
    RAISE EXCEPTION 'Age cannot be negative';
  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' field is not negative before inserting or updating a row in the 'persons' table.
Execution Table
StepOperationTrigger Fired?Validation CheckResultAction
1Insert person with age=25Yes25 < 0 ?FalseInsert allowed
2Insert person with age=-5Yes-5 < 0 ?TrueError raised, insert aborted
3Update person age to 30Yes30 < 0 ?FalseUpdate allowed
4Update person age to -1Yes-1 < 0 ?TrueError raised, update aborted
5Delete personNoNo validation neededN/ADelete allowed
💡 Operations stop or continue based on validation result; errors abort the operation.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
NEW.ageN/A25-530-1N/A
Validation resultN/AFalseTrueFalseTrueN/A
Operation statusN/AAllowedAbortedAllowedAbortedAllowed
Key Moments - 2 Insights
Why does the trigger stop the insert when age is negative?
Because the validation check in the trigger function returns True for NEW.age < 0, it raises an exception which aborts the operation, as shown in execution_table rows 2 and 4.
Does the trigger run on DELETE operations?
No, the trigger is defined for BEFORE INSERT OR UPDATE only, so it does not run on DELETE, as shown in execution_table row 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 2 when inserting age -5?
AInsert allowed
BError raised, insert aborted
CTrigger does not fire
DAge is set to 0 automatically
💡 Hint
Check the 'Result' and 'Action' columns in execution_table row 2.
At which step does the trigger NOT fire?
AStep 1
BStep 3
CStep 5
DStep 4
💡 Hint
Look at the 'Trigger Fired?' column in execution_table.
If the trigger function did not return NEW at the end, what would happen?
AThe operation would fail with an error
BThe operation would still succeed
CThe trigger would run twice
DThe data would be inserted with NULL values
💡 Hint
In PostgreSQL triggers, returning NEW is required to allow the operation to proceed.
Concept Snapshot
Trigger for data validation:
- Define a trigger function that checks data conditions.
- Attach trigger BEFORE INSERT or UPDATE on a table.
- If validation fails, raise an exception to stop operation.
- If validation passes, return NEW to continue.
- Triggers help enforce rules automatically on data changes.
Full Transcript
A trigger for data validation in PostgreSQL runs automatically before data changes like insert or update. It calls a function that checks if the new data meets rules, such as age not being negative. If the data is invalid, the function raises an error and stops the change. If valid, it returns the new data to allow the change. This process helps keep data clean and correct without manual checks.

Practice

(1/5)
1. What is the main purpose of a trigger in PostgreSQL for data validation?
easy
A. To create new tables based on existing ones
B. To speed up query execution by indexing data
C. To automatically check and enforce rules on data before it is saved
D. To backup the database automatically

Solution

  1. Step 1: Understand trigger role

    Triggers run automatically when data changes, allowing checks on data.
  2. Step 2: Identify validation purpose

    Data validation means checking data correctness before saving it.
  3. Final Answer:

    To automatically check and enforce rules on data before it is saved -> Option C
  4. Quick Check:

    Trigger = automatic data check [OK]
Hint: Triggers run automatically to check data before saving [OK]
Common Mistakes:
  • Thinking triggers speed up queries
  • Confusing triggers with backups
  • Assuming triggers create tables
2. Which of the following is the correct way to declare a BEFORE INSERT trigger in PostgreSQL?
easy
A. CREATE TRIGGER trg BEFORE INSERT ON table_name EXECUTE FUNCTION func_name;
B. CREATE TRIGGER trg AFTER INSERT ON table_name EXECUTE PROCEDURE func_name();
C. CREATE TRIGGER trg BEFORE INSERT ON table_name EXECUTE PROCEDURE func_name();
D. CREATE TRIGGER trg BEFORE INSERT ON table_name EXECUTE FUNCTION func_name();

Solution

  1. Step 1: Recall PostgreSQL trigger syntax

    PostgreSQL uses EXECUTE FUNCTION for triggers since version 11.
  2. Step 2: Identify correct timing and syntax

    BEFORE INSERT triggers run before inserting data; syntax must match.
  3. Final Answer:

    CREATE TRIGGER trg BEFORE INSERT ON table_name EXECUTE FUNCTION func_name(); -> Option D
  4. Quick Check:

    BEFORE INSERT + EXECUTE FUNCTION = CREATE TRIGGER trg BEFORE INSERT ON table_name EXECUTE FUNCTION func_name(); [OK]
Hint: Use EXECUTE FUNCTION for triggers in PostgreSQL 11+ [OK]
Common Mistakes:
  • Using EXECUTE PROCEDURE instead of EXECUTE FUNCTION
  • Confusing BEFORE and AFTER timing
  • Missing parentheses after function name
3. Given this trigger function to prevent negative prices:
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?
medium
A. An error is raised and the insert is stopped
B. The row is inserted with price -5
C. The price is automatically set to 0
D. The trigger is ignored and insert proceeds

Solution

  1. Step 1: Analyze trigger function logic

    The function checks if NEW.price is less than 0 and raises an exception if true.
  2. Step 2: Understand RAISE EXCEPTION effect

    RAISE EXCEPTION stops the operation and returns an error to the user.
  3. Final Answer:

    An error is raised and the insert is stopped -> Option A
  4. Quick Check:

    Negative price triggers error [OK]
Hint: RAISE EXCEPTION stops insert on invalid data [OK]
Common Mistakes:
  • Assuming data is inserted anyway
  • Thinking price auto-corrects
  • Ignoring trigger effects
4. You wrote this trigger function:
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?
medium
A. RAISE EXCEPTION syntax is incorrect
B. The trigger is not attached to the table
C. The function does not return NEW
D. The trigger function is missing LANGUAGE plpgsql

Solution

  1. Step 1: Check function correctness

    The function correctly raises exception and returns NEW, syntax is fine.
  2. Step 2: Consider trigger attachment

    If no error occurs, likely the trigger is not linked to the table to run the function.
  3. Final Answer:

    The trigger is not attached to the table -> Option B
  4. Quick Check:

    Trigger must be attached to run function [OK]
Hint: Attach trigger to table to activate validation [OK]
Common Mistakes:
  • Forgetting to create the trigger after function
  • Assuming function runs without trigger
  • Misreading RAISE EXCEPTION syntax
5. You want to ensure that a user's email is unique and not empty using a trigger. Which approach correctly combines data validation and uniqueness check in PostgreSQL?
hard
A. Create a BEFORE INSERT OR UPDATE trigger that raises exception if NEW.email is empty or exists in the table
B. Use a UNIQUE constraint on email column only, no trigger needed
C. Create an AFTER INSERT trigger that deletes duplicates after insertion
D. Use a trigger that sets empty emails to a default value

Solution

  1. Step 1: Understand validation needs

    Email must be non-empty and unique before saving data.
  2. 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.
  3. Final Answer:

    Create a BEFORE INSERT OR UPDATE trigger that raises exception if NEW.email is empty or exists in the table -> Option A
  4. Quick Check:

    Validate and check uniqueness before insert/update [OK]
Hint: Use BEFORE trigger to check and stop invalid data [OK]
Common Mistakes:
  • Relying only on UNIQUE constraint without empty check
  • Using AFTER trigger to fix duplicates (too late)
  • Setting default instead of raising error