0
0
PostgreSQLquery~5 mins

Trigger for data validation in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a trigger in PostgreSQL?
A trigger is a special procedure that automatically runs when certain events happen in the database, like inserting or updating data.
Click to reveal answer
beginner
How can triggers help with data validation?
Triggers can check data before it is saved and stop the action if the data does not meet rules, ensuring only valid data is stored.
Click to reveal answer
intermediate
What is the difference between BEFORE and AFTER triggers?
BEFORE triggers run before the data change happens, so they can prevent invalid data. AFTER triggers run after the change, useful for logging or actions that don't block data.
Click to reveal answer
intermediate
Write a simple trigger function in PostgreSQL that checks if a new user's age is at least 18.
CREATE 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;
Click to reveal answer
intermediate
How do you attach a trigger function to a table for INSERT events?
Use CREATE TRIGGER with the table name, specify BEFORE INSERT, and link the trigger function. Example: CREATE TRIGGER validate_age BEFORE INSERT ON users FOR EACH ROW EXECUTE FUNCTION check_age();
Click to reveal answer
What event would you use a BEFORE trigger for?
ATo create a new table
BTo log data after it is inserted
CTo delete data automatically
DTo check data before it is inserted or updated
Which language is commonly used to write PostgreSQL trigger functions?
APL/pgSQL
BPython
CJavaScript
DHTML
What happens if a trigger raises an exception during data validation?
AThe data change continues anyway
BThe data change is stopped and an error is shown
CThe database restarts
DThe trigger is ignored
Which statement correctly creates a trigger for validating data on INSERT?
ACREATE TRIGGER validate BEFORE UPDATE ON table EXECUTE FUNCTION validate_func();
BCREATE TRIGGER validate AFTER DELETE ON table EXECUTE FUNCTION validate_func();
CCREATE TRIGGER validate BEFORE INSERT ON table FOR EACH ROW EXECUTE FUNCTION validate_func();
DCREATE TRIGGER validate ON table FOR EACH STATEMENT EXECUTE FUNCTION validate_func();
Triggers are useful for:
AAutomatically enforcing rules on data changes
BManually editing data in tables
CBacking up the database
DCreating user accounts
Explain how a trigger can be used to validate data before inserting it into a table.
Think about the timing of the trigger and what happens if data is wrong.
You got /4 concepts.
    Describe the steps to create and attach a trigger function for data validation in PostgreSQL.
    Consider both the function and the trigger creation commands.
    You got /4 concepts.