Sub topic 9
Making Views Modifiable with INSTEAD OF Triggers
This chapter assumes you can write basic PL/SQL, know how row-level triggers use :OLD and :NEW, and understand transactions. You will learn why some views reject DML, how an INSTEAD OF trigger fixes that, and which mistakes to avoid.
Why Some Views Reject DML
A view is a stored query. Oracle can pass an INSERT, UPDATE, or DELETE on a view through to its base table when each view row maps to exactly one row of one table. Many views break that rule. A view cannot be updated directly if it contains any of these:
- A join of several tables, in most cases.
DISTINCT,GROUP BY, or aggregate functions.- Set operators such as
UNION. - Row-limiting or analytic constructs.
When you run DML on such a view, Oracle raises an error such as ORA-01732 ("data manipulation operation not legal on this view") or ORA-01779 for a column that cannot be modified through a join view.
An INSTEAD OF trigger solves this. It is a row-level trigger defined on a view. When DML hits the view, Oracle does not try to apply it. It runs your trigger body instead, and your code decides which base tables to change.
Setting Up an Example
The examples use a view that joins employees and departments.
CREATE OR REPLACE VIEW emp_dept_v AS
SELECT e.employee_id,
e.last_name,
e.department_id,
d.department_name
FROM employees e
JOIN departments d
ON d.department_id = e.department_id;An INSERT into this view fails, because the view spans two tables and Oracle cannot tell which table should receive the row.
Creating an INSTEAD OF Trigger
The following trigger redirects an insert on the view into an insert on employees.
CREATE OR REPLACE TRIGGER emp_dept_v_ioi
INSTEAD OF INSERT ON emp_dept_v
FOR EACH ROW
BEGIN
INSERT INTO employees (employee_id, last_name, department_id)
VALUES (:NEW.employee_id, :NEW.last_name, :NEW.department_id);
END emp_dept_v_ioi;
/Now this statement works:
INSERT INTO emp_dept_v (employee_id, last_name, department_id)
VALUES (300, 'Ng', 10);The trigger fires once for each row the statement would have inserted. The :NEW values come from the column list of the INSERT against the view. The department_name column was not supplied, so :NEW.department_name is NULL. The trigger does not use it, because the department already exists in departments.
Rules That Set INSTEAD OF Triggers Apart
- They can only be created on views, not on tables.
- They are always row-level. Oracle fires them for each row, and you do not write
FOR EACH ROWas a choice. In current Oracle releases the clause is accepted and the trigger is row-level either way. Writing it keeps the code consistent with other row triggers. - They have no
BEFOREorAFTERtiming. The trigger replaces the operation. - They cannot have a
WHENclause or anUPDATE OFcolumn list in the way table triggers can. Put any conditions inside the body withIF. - You can name
INSERT,UPDATE,DELETE, or a combination withOR.
Handling UPDATE and DELETE
A view is usually modified in more than one way, so you normally write one trigger per event or one trigger for all three. This version uses the event predicates from the earlier chapter.
CREATE OR REPLACE TRIGGER emp_dept_v_iod
INSTEAD OF UPDATE OR DELETE ON emp_dept_v
FOR EACH ROW
BEGIN
IF UPDATING THEN
UPDATE employees
SET last_name = :NEW.last_name,
department_id = :NEW.department_id
WHERE employee_id = :OLD.employee_id;
ELSE
DELETE FROM employees
WHERE employee_id = :OLD.employee_id;
END IF;
END emp_dept_v_iod;
/Three points matter here:
- Use
:OLD.employee_idto locate the base row. It identifies the row the user selected through the view, even if the same statement changes the key. :NEWis available forINSERTandUPDATE.:OLDis available forUPDATEandDELETE.- The view's
department_namecolumn comes fromdepartments. If a user tries to update it through the view, your trigger must decide what that means. The trigger above ignores it. You could instead updatedepartments, or raise an error.
The next table summarizes which values exist for each event.
| Event on the view | `:OLD` | `:NEW` | Typical base-table action |
|---|---|---|---|
| INSERT | Not available (all `NULL`) | Available | Insert into one or more tables |
| UPDATE | Available | Available | Update base rows located with `:OLD` keys |
| DELETE | Available | Not available (all `NULL`) | Delete base rows located with `:OLD` keys |
How the Statement Flows
The diagram shows the path of a DML statement against a join view with an INSTEAD OF trigger.
Touching More Than One Table
An INSTEAD OF trigger can change several tables in one body. Suppose that a new employee may come with a new department. The trigger below creates the department when it does not exist, then inserts the employee.
CREATE OR REPLACE TRIGGER emp_dept_v_ioi2
INSTEAD OF INSERT ON emp_dept_v
FOR EACH ROW
DECLARE
l_count PLS_INTEGER;
BEGIN
SELECT COUNT(*)
INTO l_count
FROM departments
WHERE department_id = :NEW.department_id;
IF l_count = 0 THEN
INSERT INTO departments (department_id, department_name)
VALUES (:NEW.department_id, :NEW.department_name);
END IF;
INSERT INTO employees (employee_id, last_name, department_id)
VALUES (:NEW.employee_id, :NEW.last_name, :NEW.department_id);
END emp_dept_v_ioi2;
/Do not keep this trigger alongside emp_dept_v_ioi. Two INSTEAD OF INSERT triggers on one view would both run, and the second would insert a duplicate employee. Replace the first trigger, or drop it, before you create the second.
Edge Cases and Gotchas
- Rows affected. Oracle reports the number of rows the statement processed, which is the number of times the trigger fired. It does not check what your body did. If the body does nothing, the statement still reports success.
- Visibility. After the trigger inserts a row, a query on the view returns it only if the row satisfies the view's join. An employee whose
department_idhas no matching department will not appear inemp_dept_v, even though the insert succeeded. WITH CHECK OPTION. This option is enforced by Oracle's own path for DML. With an INSTEAD OF trigger, your code is responsible for any equivalent check.- Constraints. Constraints on the base tables still apply. A bad
department_idraises a foreign key error from inside the trigger, and the whole statement is rolled back. - Transactions. The trigger runs inside the caller's transaction. It must not issue
COMMITorROLLBACK. RETURNINGclause.INSERT ... RETURNINGagainst a view with an INSTEAD OF trigger returns values from:NEWas the trigger left them, which is not the same as reading the base table. Treat it with care.- Nested views and bulk operations. A row-level trigger on a view fires once for each row, so a large
INSERT ... SELECTinto the view runs your body many times. For heavy loads, write directly to the base tables.
When to Use This Pattern
INSTEAD OF triggers are a good fit when:
- An existing application expects to modify a view, and you cannot change its SQL.
- You want to hide a table design, for example after splitting one table into two, and keep the old name working through a view.
- You want one controlled entry point that validates data before it writes to several tables.
They are a poor fit when you can change the application. A plain procedure with explicit INSERT statements is easier to read and test, and it does not hide work behind what looks like a simple INSERT.
Verifying the Trigger
After the creation, check that the triggers are valid and see the result of a test insert.
SELECT trigger_name, trigger_type, triggering_event, status
FROM user_triggers
WHERE table_name = 'EMP_DEPT_V';The TRIGGER_TYPE column shows INSTEAD OF for these triggers, and BASE_OBJECT_TYPE shows VIEW. If STATUS is ENABLED but a statement still fails, run SHOW ERRORS TRIGGER emp_dept_v_ioi to see compile errors.
Exercise
A view emp_dept_v has one INSTEAD OF DELETE trigger whose body deletes from employees where employee_id = :OLD.employee_id. A user runs DELETE FROM emp_dept_v WHERE department_id = 10 and 4 rows match. How many times does the trigger body run, and why should the DELETE in the body use :OLD instead of :NEW?
Show answer
The trigger fires 4 times, once for each row the statement selects through the view. :NEW is not available for a DELETE (all its fields are NULL), so :OLD is the only way to identify the base row to remove.
Exercise
Why is it a mistake to create two INSTEAD OF INSERT triggers on the same view when each one inserts the employee row?
Show answer
Both triggers fire for every inserted row, so the employee row is inserted twice. This causes a duplicate key error or duplicate data. Keep one trigger, or give each trigger a different job and set their order with FOLLOWS.