Sub topic 8
Keeping writes inside the view with WITH CHECK OPTION
This chapter assumes you can create and query a view, that you know the basics of INSERT, UPDATE and DELETE, and that you have seen which views are updatable. The examples use the employees and departments tables from earlier chapters. Syntax is shown for PostgreSQL. MySQL and Oracle behave similarly, and the differences are noted where they matter.
The problem: a write that escapes the view
An updatable view lets you write through it to the base table. The database does not stop you from writing a row that the view then cannot show. Consider this view:
CREATE VIEW active_employees AS
SELECT id, name, salary, status, department_id
FROM employees
WHERE status = 'active';The view is simple, so it is updatable. Now run this statement:
INSERT INTO active_employees (id, name, salary, status, department_id)
VALUES (2, 'Ben', 4800, 'inactive', NULL);The insert succeeds. The row lands in employees, but SELECT * FROM active_employees will never return it, because its status is inactive. The row vanished from the caller's point of view the moment it was written.
The same thing happens with updates:
UPDATE active_employees
SET status = 'inactive'
WHERE id = 1;Employee 1 is now outside the view. The caller has "lost" the row, and nothing warned them.
Sometimes this is what you want. A soft-delete flow may rely on it. When the view is meant to be a boundary, it is a bug. WITH CHECK OPTION turns the view's WHERE clause into a rule that writes must obey.
Adding WITH CHECK OPTION
Put the clause at the end of the view definition:
CREATE OR REPLACE VIEW active_employees AS
SELECT id, name, salary, status, department_id
FROM employees
WHERE status = 'active'
WITH CHECK OPTION;After each INSERT or UPDATE through the view, the database checks that the new row satisfies the view's WHERE condition. If it does not, the statement fails and no change is made.
-- Succeeds: the new row satisfies the view's WHERE clause.
INSERT INTO active_employees (id, name, salary, status, department_id)
VALUES (1, 'Ana', 5000, 'active', NULL);
-- Fails: the new row would not be visible through the view.
INSERT INTO active_employees (id, name, salary, status, department_id)
VALUES (2, 'Ben', 4800, 'inactive', NULL);PostgreSQL reports the failure as new row violates check option for view "active_employees". Other systems use different wording and error codes, such as ORA-01402 in Oracle.
-- Also fails: the updated row would leave the view.
UPDATE active_employees
SET status = 'inactive'
WHERE id = 1;Three points are worth remembering:
- The check applies to the row after the change. For an UPDATE, it is the new values that count.
- The check applies only to INSERT and UPDATE. A DELETE through the view is limited by the view's own
WHEREclause, because you can only delete rows the view shows. - The check applies only to writes made through this view. Anyone who writes directly to
employeesis not affected.
How the check runs
Base table constraints such as NOT NULL, PRIMARY KEY and foreign keys are enforced as well. The view check is an extra test on top of them.
Only the rows you write are tested
The check looks at the row being written. It does not re-test other rows. Updating one employee to a value that stays inside the view is accepted:
UPDATE active_employees
SET salary = 5500
WHERE id = 1;The row still has status active, so it passes.
A subtle case follows from this. Suppose the view's condition depends on a column the statement does not touch, and the base table already contains rows that violate the condition. Those rows are not visible through the view, so you cannot update them through it. Rows that are visible always satisfy the condition, so a write that leaves the filtered columns alone always passes.
Columns that are not in the view
The WHERE clause can use a column that the view does not select. This is legal:
CREATE VIEW engineering_staff AS
SELECT id, name, salary
FROM employees
WHERE department_id = 10
WITH CHECK OPTION;Here department_id is hidden. An INSERT through this view cannot supply a department, so the new row gets the column default, usually NULL. NULL is not equal to 10, so the check fails and every insert is rejected. To make inserts work, include department_id in the view's column list, or give the base column a default of 10, which is rarely a good idea.
This is a common reason a WITH CHECK OPTION view seems to refuse every insert. Check which columns the WHERE clause needs and make sure the view exposes them.
LOCAL and CASCADED
Views can be built on other views. When more than one level has a check option, the standard offers two modes:
WITH LOCAL CHECK OPTIONtests the new row against this view'sWHEREclause only. It also tests the conditions of underlying views that themselves have a check option.WITH CASCADED CHECK OPTIONtests the new row against this view's condition and against the conditions of every underlying view, whether or not those views declare a check option.
Plain WITH CHECK OPTION means CASCADED. Here is an example in PostgreSQL syntax:
CREATE VIEW well_paid_employees AS
SELECT id, name, salary, status, department_id
FROM employees
WHERE salary >= 4000;
CREATE VIEW well_paid_active_employees AS
SELECT id, name, salary, status, department_id
FROM well_paid_employees
WHERE status = 'active'
WITH CASCADED CHECK OPTION;An insert through well_paid_active_employees must have status active and a salary of at least 4000. If the outer view used LOCAL instead, the salary test would be skipped, because well_paid_employees has no check option of its own.
| Mode | Tests this view's WHERE | Tests underlying views' WHERE |
|---|---|---|
| `CASCADED` (default) | Yes | Always |
| `LOCAL` | Yes | Only for views that declare a check option |
Support differs. PostgreSQL and MySQL accept both keywords. Oracle supports WITH CHECK OPTION without the LOCAL and CASCADED keywords, and its check covers the view's own condition. Check your system's documentation before relying on nested behavior.
Limits of the check
- It applies only to updatable views. A view that is not updatable, for example one with
GROUP BYorDISTINCT, cannot take the clause. Most systems raise an error when you try. - It tests the condition as written. If the
WHEREclause calls a non-deterministic function such asCURRENT_DATE, a row can pass the check today and fall outside the view tomorrow. - A view that joins tables checks only the part of the condition that applies to the table being written, and many systems restrict writes through joins to one base table at a time.
- It adds a small cost to each write, because the condition is evaluated on the new row.
Choosing between WITH CHECK OPTION and alternatives
| Need | Better tool |
|---|---|
| Writes through this view must stay inside its filter | `WITH CHECK OPTION` |
| A rule must hold for every writer, whatever path they use | `CHECK` constraint on the table |
| Rows should be allowed to leave the view, for example soft delete | A view without the clause |
| Row filtering by user, applied to all access paths | Row-level security, where the database supports it |
WITH CHECK OPTION fits best where a view is the interface for a team or application, such as a view that exposes one department's rows and should never accept rows for another department.
Worked example: a department boundary
Create a view for one department with the department column visible, so inserts can satisfy the check:
CREATE VIEW sales_employees AS
SELECT id, name, salary, status, department_id
FROM employees
WHERE department_id = 20
WITH CHECK OPTION;
-- Accepted: department 20.
INSERT INTO sales_employees (id, name, salary, status, department_id)
VALUES (10, 'Cleo', 4200, 'active', 20);
-- Rejected: department 30 is outside the view.
INSERT INTO sales_employees (id, name, salary, status, department_id)
VALUES (11, 'Dev', 4100, 'active', 30);
-- Rejected: moving a visible row to another department.
UPDATE sales_employees
SET department_id = 30
WHERE id = 10;This assumes departments 20 and 30 exist in departments. Combined with GRANT INSERT, UPDATE ON sales_employees to a role, as covered in the security chapter, the role can maintain its own department's rows and cannot move data elsewhere.
Exercise
A view is defined as SELECT id, name FROM employees WHERE department_id = 10 WITH CHECK OPTION. Every INSERT through it fails, even for people in department 10. Why, and how would you fix it?
Show answer
The WHERE clause uses department_id, but the view does not expose that column. An INSERT cannot supply it, so the new row gets the column default, usually NULL. NULL = 10 is not true, so the check rejects the row. Fix it by adding department_id to the view's SELECT list so inserts can provide the value 10.
Exercise
View a is defined on employees with WHERE salary >= 4000 and no check option. View b is defined on a with WHERE status = 'active' WITH LOCAL CHECK OPTION. Is an insert through b of an active employee with salary 1000 accepted? What changes if b uses CASCADED?
Show answer
With LOCAL, the insert is accepted, because only b's own condition is tested and a has no check option. With CASCADED, it is rejected, because the condition of every underlying view, including salary >= 4000, must also hold.