Google News
logo
HSQLDB - Interview Questions
How do you create a trigger in HSQLDB?
In HSQLDB, you can create triggers using SQL commands. Here's the basic syntax for creating a trigger:
CREATE TRIGGER trigger_name
BEFORE|AFTER|INSTEAD OF event_type ON table_name
FOR EACH ROW
[WHEN condition]
[trigger_action]?

Let's break down the components of this syntax :

* trigger_name : The name of the trigger you want to create.
* BEFORE|AFTER|INSTEAD OF : Specifies when the trigger should execute. BEFORE triggers execute before the event, AFTER triggers execute after the event, and INSTEAD OF triggers are used for views and execute instead of the event.
* event_type : Specifies the type of event that triggers the execution of the trigger (e.g., INSERT, UPDATE, DELETE).
* ON table_name : Specifies the table on which the trigger should be created.
* FOR EACH ROW : Indicates that the trigger should be executed once for each row affected by the event.
* [WHEN condition] : Optional condition that determines whether the trigger should execute based on certain criteria.
* [trigger_action] : The SQL statements or actions to be executed when the trigger fires.
Here's an example of creating a trigger in HSQLDB :
CREATE TRIGGER update_employee_salary
AFTER UPDATE OF salary ON Employee
FOR EACH ROW
BEGIN ATOMIC
    IF NEW.salary > OLD.salary THEN
        INSERT INTO SalaryHistory (employee_id, old_salary, new_salary, change_date)
        VALUES (NEW.employee_id, OLD.salary, NEW.salary, CURRENT_TIMESTAMP);
    END IF;
END;?

In this example :

* The trigger named update_employee_salary is created to execute after an update of the salary column in the Employee table.
* For each row affected by the update, the trigger inserts a record into the SalaryHistory table, recording the change in salary along with the employee ID and the date of the change.
Advertisement