PostgreSQL Drop View
Summary: in this tutorial, you will learn how to use the PostgreSQL DROP VIEW
statement to delete a view from your database.
Introduction to PostgreSQL DROP VIEW statement
The DROP VIEW
statement allows you to remove a view from the database.
Here’s the basic syntax of the DROP VIEW
statement:
In this syntax:
- First, specify the name of the view in the
DROP VIEW
clause. - Second, use
IF EXISTS
to prevent an error if the view does not exist. PostgreSQL will issue a notice instead of an error when you attempt to remove a non-existing view. TheIF EXISTS
is optional. - Third, use
CASCADE
option to remove dependent objects along with the view or theRESTRICT
option to reject the removal of the view if other objects depend on the view. TheRESTRICT
option is the default.
Dropping multiple views
To drop multiple views simultaneously, you specify the view names separated by commas after the DROP VIEW
keywords:
Permissions
To execute the DROP VIEW
statement, you need to be the owner of the view or have a DROP
privilege on it.
PostgreSQL DROP VIEW statement examples
We’ll use the following tables film
, film_category
, and category
from the sample database:
Creating views for practicing
The following statement creates a new view called film_info
based on the film
, film_category
, and category
tables:
The following statement creates a view called horror_film
based on the film_info
view:
The following statement creates a view called comedy_film
based on the film_master
view:
The following statement creates a view called film_category_stat
that returns the number of films by category:
The following creates a view called film_length_stat
that returns the total length of films for each category:
1) Using the DROP VIEW statement to drop one view example
The following example uses the DROP VIEW
statement to drop the comedy_film
view:
2) Using the DROP VIEW statement to drop a view that has dependent objects
The following statement uses the DROP VIEW
statement to drop the film_info
view:
PostgreSQL issued an error:
The film_info
has a dependent object which is the view horror_film
.
To drop the view film_info
, you need to drop its dependent object first or use the CASCADE
option like this:
This statement drops the film_info
view as well as its dependent object which is the horror_film
. It issued the following notice:
3) Using the DROP VIEW statement to drop multiple views
The following statement uses a single DROP VIEW
statement to drop multiple views:
Summary
- Use the
DROP VIEW
statement to remove one or more views from the database. - Use the
IF EXISTS
option to remove a view if it exists. - Use the
CASCADE
option to remove a view and its dependent objects recursively.