Sub topic 5
Replacing and dropping views
This chapter covers changing and removing views once they exist. It assumes you can write SELECT queries with joins, have created a view with CREATE VIEW, and know that a view stores a query, not data. The sample tables are departments and employees from earlier chapters.
Why view changes need care
A view has no rows of its own, so changing it is cheap. Nothing is copied or rebuilt. The risk comes from the objects and people that depend on the view: other views, reports, application queries and granted privileges. A change that looks harmless in the view's definition can break all of them.
There are three ways to change a view:
- Replace the definition in place with
CREATE OR REPLACE VIEW. - Drop the view and create it again.
- Make a small change, such as renaming it, with
ALTER VIEW.
The syntax differs between systems. This chapter uses PostgreSQL behavior as the reference and notes where MySQL, Oracle and SQL Server differ.
Replacing a view in place
CREATE OR REPLACE VIEW creates the view if it does not exist. If it does exist, the statement swaps in the new query. This example adds a filter to employee_directory:
-- Syntax shown works in PostgreSQL, MySQL and Oracle; other systems differ.
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';Callers that run SELECT * FROM employee_directory get the new result with no other change. The view keeps its identity, so anything that depends on it, including privileges, stays in place.
The column rules in PostgreSQL
PostgreSQL only lets CREATE OR REPLACE VIEW make changes that cannot break existing callers. The new query must:
- Return the same columns, in the same order, with the same names and data types as the old query.
- Add any new columns only at the end of the list.
The WHERE clause above passes because it changes which rows come back, not the shape of the result. The following statement does not pass. It puts a new column in the middle of the list:
CREATE OR REPLACE VIEW employee_directory AS
SELECT e.id,
e.name,
e.email,
d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id;PostgreSQL rejects it with an error such as cannot change name of view column "department" to "email". The fix is to append the column:
CREATE OR REPLACE VIEW employee_directory AS
SELECT e.id,
e.name,
d.name AS department,
e.email
FROM employees e
JOIN departments d ON d.id = e.department_id;Existing queries that select id, name and department by name keep working. Queries that use SELECT * now also receive email, which may or may not be what you want.
Other systems are less strict. MySQL accepts a replacement with different columns. Oracle does too, but it marks dependent objects invalid until they are recompiled. Check your system's rules before you rely on either behavior.
Removing a column
Dropping a column from the output is never allowed with CREATE OR REPLACE VIEW in PostgreSQL. Any query that uses the column would break. To remove a column you have to drop and recreate the view, as the next sections show.
Dropping a view
DROP VIEW removes the view definition. The underlying tables and their data are not touched.
DROP VIEW employee_directory;If the view does not exist, this raises an error. Adding IF EXISTS turns that error into a notice, which makes scripts safe to rerun:
DROP VIEW IF EXISTS employee_directory;IF EXISTS is supported by PostgreSQL, MySQL and SQL Server (2016 and later). Oracle does not support it for DROP VIEW, so Oracle scripts catch the error instead.
You can drop several views in one statement in PostgreSQL and MySQL:
DROP VIEW IF EXISTS employee_summary, active_employees;Dependencies
Suppose a second view reads from employee_directory:
CREATE VIEW engineering_directory AS
SELECT id, name
FROM employee_directory
WHERE department = 'Engineering';PostgreSQL refuses to drop employee_directory while engineering_directory depends on it:
DROP VIEW employee_directory;
-- ERROR: cannot drop view employee_directory because other objects depend on itTwo options exist:
- Drop the dependent views first, starting with the outermost one.
- Use
DROP VIEW employee_directory CASCADE, which also drops every dependent object.
CASCADE is convenient and dangerous. It can remove views you did not know existed. Run the plain DROP VIEW first and read the error message, which lists the dependents. If you run CASCADE, check its notice output afterward.
MySQL and SQL Server behave differently. They allow the drop and leave the dependent view broken. It fails with an error the next time someone queries it. This is the worse outcome, because the problem shows up later and far from the cause.
Drop and recreate
When CREATE OR REPLACE is not allowed, the usual route is a drop and recreate inside a transaction. PostgreSQL supports transactional DDL, so other sessions never see a moment when the view is missing:
BEGIN;
DROP VIEW IF EXISTS employee_directory;
CREATE VIEW employee_directory AS
SELECT e.id,
d.name AS department
FROM employees e
JOIN departments d ON d.id = e.department_id;
COMMIT;This version removes the name column. It succeeds only if no other view depends on employee_directory. Otherwise you must recreate the dependents too, in the same transaction.
A dropped view takes its privileges with it. A recreated view starts with none, so grants made earlier, such as GRANT SELECT ON employee_directory TO analyst, must be repeated:
GRANT SELECT ON employee_directory TO analyst;MySQL and Oracle's CREATE OR REPLACE VIEW keeps existing grants. This is a good reason to prefer it when the change is allowed.
Oracle and MySQL commit DDL statements immediately, so the transaction wrapper above gives no protection there. In those systems, keep the gap between drop and create as short as possible and run the script during a quiet period.
Renaming and other changes with ALTER VIEW
ALTER VIEW does not change the query in PostgreSQL. It changes properties of the view:
ALTER VIEW employee_directory RENAME TO staff_directory;
ALTER VIEW staff_directory RENAME COLUMN department TO dept_name;
ALTER VIEW staff_directory OWNER TO hr_admin;Other systems use the statement differently:
| System | What `ALTER VIEW` does |
|---|---|
| PostgreSQL | Renames the view or a column, changes owner, schema or options. Does not change the query. |
| MySQL | Replaces the whole definition, like `CREATE OR REPLACE VIEW`. |
| SQL Server | Replaces the whole definition. There is no `CREATE OR REPLACE`. |
| Oracle | Recompiles the view or changes constraints. Use `CREATE OR REPLACE VIEW` to change the query. |
SQL Server has no CREATE OR REPLACE VIEW before the CREATE OR ALTER VIEW form added in SQL Server 2016 SP1. Scripts for older versions drop and recreate, or use ALTER VIEW.
A rename does not rewrite other views that mention the old name in PostgreSQL. They refer to the view by internal identifier, so they keep working. In MySQL they break, because the stored definition holds the old name.
A safe change routine
For a view that other people or programs use, work in this order:
- List the dependents. In PostgreSQL, query
pg_dependor run a plainDROP VIEWinside a transaction and roll it back. - Try
CREATE OR REPLACE VIEWfirst. It preserves grants and dependents. - If the system rejects it, plan a drop and recreate, including dependents and grants.
- Run the change in a transaction where the system supports it.
- Test with a query against the view and with a query against each dependent view.
How a change flows
The diagram shows how to choose between the options.
Common mistakes
- Reordering columns. Putting a new column in the middle makes PostgreSQL reject
CREATE OR REPLACE VIEW. Append it instead. - Forgetting grants after a recreate. The view works for the owner and fails for everyone else with a permission error.
- Using
CASCADEas a shortcut. It hides the dependency list you needed to read. - Assuming a drop is safe because the data is safe. The base tables are untouched, but any query that used the view now fails.
- Relying on
SELECT *in a view definition. In PostgreSQL the star is expanded when the view is created. Columns added to the table later do not appear in the view until you replace it.
The last point is easy to miss. Adding a column to employees does not change employee_directory, even if its query said SELECT e.*. You must run CREATE OR REPLACE VIEW again to pick it up, and the added column then has to go at the end of the output list.
Exercise
In PostgreSQL, employee_directory has the columns id, name and department. A second view, engineering_directory, selects from it. You want to add email as a fourth column, and later remove name. Which statement or approach do you use for each change, and what must you do after the second one?
Show answer
Adding email as the last column works with CREATE OR REPLACE VIEW employee_directory AS ..., because the existing columns keep their names, order and types. Dependents and grants stay in place. Removing name cannot be done with CREATE OR REPLACE VIEW. You must drop and recreate. Since engineering_directory depends on the view and selects name, first drop or redefine engineering_directory, then drop and recreate employee_directory without name, then recreate engineering_directory without name. Do this in one transaction. Finally repeat the GRANT statements on every recreated view.
Exercise
Why is DROP VIEW IF EXISTS employee_directory; safer in a deployment script than DROP VIEW employee_directory;, and what does neither statement do to the employees table?
Show answer
IF EXISTS turns the error for a missing view into a notice, so the script can be rerun without stopping on the first line. Neither statement changes the employees table or its rows, because a view holds only a query and no data of its own.