Bird
0
0

This trigger function is intended to prevent empty usernames:

medium📝 Debug Q7 of 15
PostgreSQL - Triggers in PostgreSQL
This trigger function is intended to prevent empty usernames:
CREATE FUNCTION check_username() RETURNS trigger AS $$ BEGIN IF NEW.username = '' THEN RAISE EXCEPTION 'Username cannot be empty'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql;
But empty usernames are still inserted. What is the problem?
AThe trigger function is missing a LANGUAGE declaration
BThe trigger is defined as AFTER INSERT instead of BEFORE INSERT
CThe comparison should use IS NULL instead of = ''
DThe function does not return OLD
Step-by-Step Solution
Solution:
  1. Step 1: Understand trigger timing effect

    AFTER INSERT triggers run after data is inserted, so cannot block insertion.
  2. Step 2: Identify correct timing for validation

    BEFORE INSERT triggers run before insert and can prevent invalid data.
  3. Final Answer:

    The trigger is defined as AFTER INSERT instead of BEFORE INSERT -> Option B
  4. Quick Check:

    Use BEFORE triggers to block invalid inserts [OK]
Quick Trick: Use BEFORE triggers to stop invalid data insertion [OK]
Common Mistakes:
  • Using AFTER triggers for validation
  • Confusing empty string with NULL
  • Omitting LANGUAGE in function

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes