Consider a table employees(id, name, salary) and a view high_earners defined as SELECT * FROM employees WHERE salary > 50000. What will be the result of this query?
UPDATE high_earners SET salary = salary + 5000 WHERE id = 3 RETURNING *;
CREATE TABLE employees (id INT PRIMARY KEY, name TEXT, salary INT); INSERT INTO employees VALUES (1, 'Alice', 60000), (2, 'Bob', 45000), (3, 'Carol', 70000); CREATE VIEW high_earners AS SELECT * FROM employees WHERE salary > 50000;
Think about whether the view filters rows and if the updated row still meets the filter.
The view high_earners filters employees with salary > 50000. The row with id=3 has salary 70000, so it is included. Updating salary to 75000 keeps it in the view. The query returns the updated row.
Which of the following views is not updatable by default in PostgreSQL?
Think about what makes a view simple enough to be updatable.
Views based on a single table without aggregation or joins are updatable. Views with joins are not updatable by default because PostgreSQL cannot determine how to update multiple tables.
Given a view v_emp_dept joining employees and departments, which option correctly creates an INSTEAD OF trigger to allow updates on the view?
INSTEAD OF triggers must be created on views, not tables, and use EXECUTE FUNCTION syntax in PostgreSQL 12+.
INSTEAD OF triggers on views intercept update commands and allow custom logic. The trigger must be created on the view, use INSTEAD OF timing, and EXECUTE FUNCTION syntax.
You have an updatable view based on a large table with a WHERE clause. Updates on the view are slow. Which approach can improve update performance?
Think about how indexes help queries and updates.
Adding an index on columns used in the WHERE clause helps PostgreSQL quickly find rows to update, improving performance. Joining with another large table or removing filters can slow down updates. Materialized views are not updatable.
Given the view definition:
CREATE VIEW v_emp AS SELECT id, name, salary, salary * 1.1 AS adjusted_salary FROM employees;
Why does this query raise an error?
UPDATE v_emp SET adjusted_salary = 80000 WHERE id = 2;
Consider which columns in a view can be updated.
Columns in a view that are computed expressions (like salary * 1.1) cannot be updated because they do not directly map to a column in the underlying table.