WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

SQL & Databases · Basic · question 18 of 100

What is a database trigger, and what are some common use cases for them?

📕 Buy this interview preparation book: 100 SQL & Databases questions & answers — PDF + EPUB for $5

A database trigger is a type of stored procedure that is automatically executed in response to a specific database event or action. Triggers can be used to enforce business rules, maintain data integrity, and perform complex database operations.

Here is an example of a database trigger:

CREATE TRIGGER update_employee_salary
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
    IF NEW.salary > OLD.salary THEN
        INSERT INTO salary_history (employee_id, old_salary, new_salary, change_date)
        VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW());
    END IF;
END

In this example, the trigger is called update_employee_salary and is fired after an update is made to the employees table. The trigger checks whether the new salary is greater than the old salary and inserts a new record into the salary_history table if it is.

Some common use cases for database triggers include:

Enforcing business rules: Triggers can be used to enforce business rules and ensure that data is entered correctly into the database. For example, a trigger could be used to ensure that a customer’s age is greater than 18 before adding them to the database.

Maintaining data integrity: Triggers can be used to maintain data integrity by preventing invalid data from being added to the database. For example, a trigger could be used to prevent a product from being added to an order if it is out of stock.

Auditing and logging: Triggers can be used to log changes made to the database for auditing purposes. For example, a trigger could be used to log changes made to a customer’s account information.

Data synchronization: Triggers can be used to synchronize data between different tables or databases. For example, a trigger could be used to update a sales summary table whenever a new order is added to the database.

Overall, database triggers provide a powerful mechanism for enforcing business rules, maintaining data integrity, and performing complex database operations. By using triggers, you can automate database tasks and ensure that data is consistently and reliably updated, making it a valuable tool for database developers and administrators.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic SQL & Databases interview — then scores it.
📞 Practice SQL & Databases — free 15 min
📕 Buy this interview preparation book: 100 SQL & Databases questions & answers — PDF + EPUB for $5

All 100 SQL & Databases questions · All topics