Can views be updated in SQL?
Under what conditions?
Yes, views can be updated in SQL, but there are conditions for when this is possible:
- Updatable Views: A view is updatable if it:
- Is based on a single table.
- Does not contain aggregation functions like COUNT(), AVG(), or SUM().
- Does not include DISTINCT, GROUP BY, JOIN, or other complex operations
that modify the set of rows.
- Non-Updatable Views: Views that use complex JOINs, aggregations, or GROUP BY
clauses are typically non-updatable.
You can still modify data through these views by using triggers, such as INSTEAD
OF triggers, which allow you to define custom behavior for updating or deleting rows.
Example of an updatable view:
CREATE VIEW simple_view AS
SELECT id, name, salary FROM employees;
- - You can now update 'simple_view' directly:
UPDATE simple_view SET salary = 60000 WHERE id = 101;