Sub topic 2
Replacing and Dropping Views
This chapter assumes you know SELECT with WHERE, joins with JOIN, CREATE TABLE and INSERT, and the basics of database users and privileges. The examples use the employees and departments tables from earlier in the tutorial.
Replacing and dropping views
Use CREATE OR REPLACE VIEW to change a view's definition without deleting it first. In PostgreSQL, the new column list must match the old one in name and order.
CREATE OR REPLACE 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
WHERE e.status = 'active';DROP VIEW removes the stored query. The base tables and their rows stay untouched. Other views that depend on the dropped view will fail, so check for dependents first.
DROP VIEW IF EXISTS employee_directory;Limiting what users can see
Grant privileges on the view instead of the base table. The analyst role below can read the columns the view exposes, but not salary or email.
GRANT SELECT ON employee_directory TO analyst;Writing data through a view
A simple view over one table, with no joins, GROUP BY, DISTINCT or aggregate functions, usually accepts INSERT, UPDATE and DELETE. The database applies the write to the base table.
CREATE VIEW active_employees AS
SELECT id, name, salary, status, department_id
FROM employees
WHERE status = 'active';
UPDATE active_employees
SET salary = 5200
WHERE id = 1;An update can move a row out of the view. Setting status to 'inactive' through this view changes the row, and the row then disappears from the view without any error.
Keeping writes inside the view with WITH CHECK OPTION
Add WITH CHECK OPTION to reject any write whose resulting row would not appear in the view.
CREATE VIEW checked_active_employees AS
SELECT id, name, salary, status, department_id
FROM employees
WHERE status = 'active'
WITH CHECK OPTION;
-- Fails: the updated row would not satisfy the view's WHERE clause.
UPDATE checked_active_employees
SET status = 'inactive'
WHERE id = 1;Exercise
Why does an UPDATE that sets status to 'inactive' succeed through activeemployees but fail through checkedactive_employees?
Show answer
activeemployees has no check option, so the row is updated and then disappears from the view. checkedactive_employees has WITH CHECK OPTION, so the database rejects any write whose resulting row fails the view's WHERE clause.