Bird
Raised Fist0
PostgreSQLquery~20 mins

Trigger for data validation in PostgreSQL - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Trigger Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Output of a trigger function enforcing age validation
Consider a PostgreSQL table users with a trigger that prevents inserting rows where age is less than 18. What will happen if you run the following insert?
INSERT INTO users (id, name, age) VALUES (1, 'Alice', 16);
PostgreSQL
CREATE OR REPLACE FUNCTION check_age() RETURNS trigger AS $$
BEGIN
  IF NEW.age < 18 THEN
    RAISE EXCEPTION 'Age must be at least 18';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER age_check BEFORE INSERT ON users
FOR EACH ROW EXECUTE FUNCTION check_age();
AThe insert fails with an error: 'Age must be at least 18'.
BThe insert is ignored silently without error.
CThe insert succeeds but age is automatically set to 18.
DThe row is inserted successfully with age 16.
Attempts:
2 left
💡 Hint
Triggers can raise exceptions to stop invalid data from being inserted.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this trigger function
Which option contains the correct syntax for a PostgreSQL trigger function that validates a non-empty username field before insert?
PostgreSQL
CREATE OR REPLACE FUNCTION validate_username() RETURNS trigger AS $$
BEGIN
  IF NEW.username = '' THEN
    RAISE EXCEPTION 'Username cannot be empty';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
ACREATE OR REPLACE FUNCTION validate_username() RETURNS trigger AS $$ BEGIN IF NEW.username = '' THEN RAISE 'Username cannot be empty'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql;
BCREATE OR REPLACE FUNCTION validate_username() RETURNS trigger AS $$ BEGIN IF NEW.username == '' THEN RAISE EXCEPTION 'Username cannot be empty'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql;
CCREATE FUNCTION validate_username() RETURNS trigger AS $$ BEGIN IF NEW.username = '' THEN RAISE EXCEPTION 'Username cannot be empty'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql;
DCREATE OR REPLACE FUNCTION validate_username() RETURNS trigger AS $$ BEGIN IF NEW.username = '' THEN RAISE EXCEPTION 'Username cannot be empty'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql;
Attempts:
2 left
💡 Hint
Check the use of 'CREATE OR REPLACE FUNCTION' and the correct comparison operator.
optimization
advanced
2:00remaining
Optimizing a trigger for multiple column validations
You want to create a trigger that validates both email and phone columns on insert or update. Which option is the most efficient way to write the trigger function?
ACreate one AFTER INSERT OR UPDATE trigger that checks email and phone and deletes the row if invalid.
BCreate one trigger function that checks both email and phone in a single BEFORE INSERT OR UPDATE trigger.
CCreate one trigger function that checks email on BEFORE INSERT and phone on BEFORE UPDATE separately.
DCreate two separate triggers: one for email validation and one for phone validation, both firing BEFORE INSERT OR UPDATE.
Attempts:
2 left
💡 Hint
Minimize the number of triggers for better performance.
🔧 Debug
advanced
2:00remaining
Debugging a trigger that does not prevent invalid data
A trigger is supposed to prevent inserting rows with salary less than 0, but invalid rows are still inserted. Which option explains the most likely cause?
PostgreSQL
CREATE OR REPLACE FUNCTION check_salary() RETURNS trigger AS $$
BEGIN
  IF NEW.salary < 0 THEN
    RAISE EXCEPTION 'Salary cannot be negative';
  END IF;
  RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER salary_check BEFORE INSERT ON employees
FOR EACH ROW EXECUTE FUNCTION check_salary();
AThe trigger function returns NULL, which skips the insert instead of raising an error.
BThe trigger is AFTER INSERT, so it cannot prevent the insert.
CThe trigger function uses RAISE EXCEPTION incorrectly and does not stop the insert.
DThe trigger is defined FOR EACH STATEMENT instead of FOR EACH ROW.
Attempts:
2 left
💡 Hint
Check what the trigger function returns to control the insert.
🧠 Conceptual
expert
2:00remaining
Understanding trigger timing and data validation
Which statement best describes why a BEFORE trigger is preferred over an AFTER trigger for data validation in PostgreSQL?
AAFTER triggers run before the data is inserted, so they can modify data before saving.
BBEFORE triggers run after the data is inserted, so they can rollback changes if invalid.
CBEFORE triggers run before the data is inserted, allowing validation and prevention of invalid data before it reaches the table.
DAFTER triggers prevent invalid data by stopping the insert before it happens.
Attempts:
2 left
💡 Hint
Think about when the data is checked relative to insertion.

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