Sub topic 7
Writing data through a view
This chapter assumes you can create and query a view and can write basic INSERT, UPDATE and DELETE statements. The examples use the employees and departments tables from earlier in the tutorial. They are written for PostgreSQL, and the chapter says where other systems differ.
What "updatable" means
A view stores no rows of its own. When you run INSERT, UPDATE or DELETE against a view, the database has to translate the statement into the same operation on a base table. That is only possible when each row you see in the view maps to exactly one row in one base table. A view with that property is called an updatable view.
The SQL standard and most databases split the question in two:
- Whether the view as a whole accepts a statement. This is decided by the shape of its defining query.
- Whether each column accepts a write. A view can be updatable even though some of its columns are read-only.
The database decides this when you run the statement, not when you create the view. CREATE VIEW succeeds for any valid query, and a non-updatable view only fails when someone tries to write to it.
A simple updatable view
This view exposes the active employees from one table. It has no WITH CHECK OPTION yet. The next chapter adds it.
CREATE VIEW active_employees AS
SELECT id, name, salary, status, department_id
FROM employees
WHERE status = 'active';Each of the three write statements works against it as if it were a table.
INSERT INTO active_employees (id, name, salary, status, department_id)
VALUES (1, 'Ana', 5000, 'active', NULL);
UPDATE active_employees
SET salary = salary * 1.05
WHERE id = 1;
DELETE FROM active_employees
WHERE id = 1;The database rewrites each statement against employees. The UPDATE becomes roughly this:
UPDATE employees
SET salary = salary * 1.05
WHERE status = 'active' -- the view's own condition
AND id = 1; -- your conditionThe view's WHERE clause is combined with yours using AND. This has two consequences:
UPDATEandDELETEcan only reach rows the view returns. An employee with status'inactive'is invisible, soDELETE FROM active_employees WHERE id = 99deletes nothing and reports zero rows affected. It does not raise an error.INSERTis not filtered. The new row goes into the base table whether or not it would appear in the view.
What makes a view non-updatable
Most systems refuse writes when the defining query has any construct that breaks the one-view-row-to-one-table-row mapping.
| Construct in the view query | Why a write cannot be mapped back |
|---|---|
| `GROUP BY`, `HAVING`, aggregate functions | One view row summarizes many base rows. |
| `DISTINCT` | Several base rows can collapse into one view row. |
| `UNION`, `INTERSECT`, `EXCEPT` | The view row could come from either of two tables. |
| Window functions | The values depend on neighboring rows. |
| `LIMIT`, `FETCH FIRST` | The view's row set changes after the write. |
| Joins across several tables | One statement may need to change several tables. Rules vary by system. |
Some of these limits differ by database. PostgreSQL's "automatically updatable" views accept only a single table or another updatable view in FROM. MySQL and Oracle allow some updates through joins.
Individual columns can be read-only in a view that is otherwise updatable:
- A column defined by an expression, such as
salary / 12 AS monthly_salary, cannot be set directly. The database cannot work out whichsalarywould produce the value you supply. - A column that is not in the view cannot be written through it.
CREATE VIEW employee_pay AS
SELECT id, name, salary, salary / 12 AS monthly_salary
FROM employees;
-- Works: salary is a plain column.
UPDATE employee_pay SET salary = 6000 WHERE id = 1;
-- Fails: monthly_salary is computed.
UPDATE employee_pay SET monthly_salary = 500 WHERE id = 1;The same applies to INSERT. You can leave the computed column out of the column list, but you cannot give it a value.
Columns the view leaves out
An INSERT through a view fills the base table's other columns with their defaults, or with NULL if there is no default. If a hidden column is NOT NULL and has no default, the insert fails.
Take a view that omits salary, which is declared NOT NULL in employees:
CREATE VIEW employee_names AS
SELECT id, name, status FROM employees;
-- Fails: salary is NOT NULL, has no default, and is not in the view.
INSERT INTO employee_names (id, name, status)
VALUES (3, 'Chloe', 'active');There are two ways to make such a view insertable:
- Add a default to the hidden column with
ALTER TABLE employees ALTER COLUMN salary SET DEFAULT 0. Use this only if the default is meaningful for your data. - Include the column in the view.
Do not add a default merely to silence the error.
Rows that leave the view
Because INSERT is unfiltered and UPDATE can change any visible column, a write can produce a row that the view no longer shows. This surprises many people.
INSERT INTO active_employees (id, name, salary, status, department_id)
VALUES (2, 'Ben', 4800, 'inactive', NULL);
SELECT * FROM active_employees WHERE id = 2; -- returns no rows
SELECT * FROM employees WHERE id = 2; -- the row is thereThe insert succeeded, and the row went into employees, yet querying the view cannot find it. An update can do the same thing:
UPDATE active_employees SET status = 'inactive' WHERE id = 1;
-- Employee 1 now disappears from active_employees.If that behavior is not what you want, WITH CHECK OPTION makes the database reject such writes. The next chapter covers it.
Views over joins and INSTEAD OF triggers
The employee_directory view from earlier joins two tables:
CREATE VIEW employee_directory AS
SELECT e.id,
e.name,
d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id;In PostgreSQL, this view is not updatable. An UPDATE against it fails with an error saying the view is not automatically updatable. Other systems may allow some updates here. MySQL, for instance, accepts an update that changes columns of only one underlying table. SQL Server has the same one-table-per-statement limit.
When you need writes through a view the database will not translate, define an INSTEAD OF trigger. This trigger runs in place of the write statement, and you code the translation yourself. PostgreSQL, SQL Server and Oracle support INSTEAD OF triggers on views. MySQL does not. This PostgreSQL example makes updates to the name and department work:
CREATE FUNCTION employee_directory_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
UPDATE employees
SET name = NEW.name,
department_id = (SELECT id FROM departments WHERE name = NEW.department)
WHERE id = OLD.id;
RETURN NEW;
END;
$$;
CREATE TRIGGER employee_directory_update
INSTEAD OF UPDATE ON employee_directory
FOR EACH ROW
EXECUTE FUNCTION employee_directory_update();If NEW.department names a department that does not exist, the subquery returns NULL and the employee ends up with no department. A production trigger should check for that case and raise an error.
The trigger approach has a cost. The write logic now lives in a trigger, away from the view definition, and anyone changing the tables must remember it. Use a trigger only when the view is a deliberate interface to the data, for example when you hide a table layout from an application.
Deciding whether a write will work
The checks the database makes follow roughly this order.
Permissions and constraints still apply
Writes through a view are checked against the base table's constraints: NOT NULL, CHECK, unique keys and foreign keys all fire as they would for a direct write.
Permissions work differently from what many people expect. Granting UPDATE on a view lets a role change rows through the view. Under the default rules in most systems, it does not need UPDATE on the base table, because the view runs with its owner's privileges. PostgreSQL 15 and later offers security_invoker views, which check privileges as the calling user instead. Check your database's rules before relying on a view as a write-access boundary.
GRANT UPDATE (salary) ON active_employees TO payroll;This grants payroll the right to update only the salary column, and only on rows that the view exposes.
Summary of practical rules
- Treat a view as writable only if you can point to a single base table behind it with no aggregation or de-duplication.
- Expect
UPDATEandDELETEto silently skip rows the view hides. - Remember that
INSERTandUPDATEcan create rows that vanish from the view unless you useWITH CHECK OPTION. - Check
NOT NULLcolumns that the view omits before promising that inserts work. - Reach for an
INSTEAD OFtrigger only when the view is a deliberate write interface.
Exercise
A view senior_staff is defined as SELECT id, name, salary FROM employees WHERE salary > 8000, with no check option. You run UPDATE senior_staff SET salary = 7000 WHERE id = 10; and it reports one row updated. Then you run UPDATE senior_staff SET salary = 7500 WHERE id = 10;. What happens, and why?
Show answer
The second statement updates zero rows and raises no error. The first update changed the base row to a salary of 7000, so employee 10 no longer satisfies salary > 8000 and is no longer visible through the view. Because the database adds the view's condition to the WHERE clause of the update, it finds no matching row. WITH CHECK OPTION would have rejected the first update.
Exercise
You define CREATE VIEW dept_totals AS SELECT department_id, SUM(salary) AS total FROM employees GROUP BY department_id;. Why does UPDATE dept_totals SET total = 0 WHERE department_id = 1; fail, and what could you add to make it succeed?
Show answer
Each row in dept_totals summarizes many employees rows, so the database cannot map total back to any specific base rows to change. The only way to make such a write succeed is an INSTEAD OF trigger (in systems that support them) that decides what the write should mean, for example by scaling every salary in the department.