PostgreSQL ALTER VIEW Statement
Summary: in this tutorial, you will learn how to use the PostgreSQL ALTER VIEW
statement to change the properties of a view.
Introduction to the PostgreSQL ALTER VIEW statement
The ALTER VIEW
statement allows you to change various properties of a view.
If you want to change the view’s defining query, use the CREATE OR REPLACE VIEW
statement.
Here’s the basic syntax of the ALTER VIEW
statement:
In this syntax:
First, specify the name of the view that you want to change in the ALTER VIEW
clause.
Second, use the IF EXISTS
option to modify the view only if it exists. The statement will issue an error if you don’t use the IF EXISTS
and attempt to change a non-existing view. But when you use the IF EXISTS
, the statement issues a notice instead. The IF EXISTS
is optional.
Third, provide the action that you want to do with the view. The action includes renaming the view, setting the view option, and so on.
Renaming a view
The following ALTER VIEW
statement changes the name of a view to the new one:
In this syntax, you specify the new view name (new_view_name
) after the RENAME TO
clause. For example:
First, create a new view called film_type
that includes the title
and rating
:
Second, change the view film_type
to film_rating
:
Changing the view option
The following ALTER VIEW
statement changes the view option:
The view_option_name
can be:
check_option
: change the check option. The valid value islocal
orcascaded
.security_barrier
: change the security-barrier property of a view. The valid value istrue
orfalse
.security_invoker
: change the security invoker of a view. The valid value istrue
orfalse
.
For example, the following changes the check option of the film_rating
view to local
:
To view the change, you can use the \d+
command in psql
:
Output:
Changing the view column
The following statement changes a column name of a view to a new one:
For example, the following statement changes the title
column of the film_rating
view to film_title
:
Here’s the new view detail:
Setting the new schema
The following statement sets the new schema for a view:
For example:
First, create a new schema called web
:
Second, change the schema of the film_rating
view to web
:
Third, verify the change (in psql
):
Output:
Summary
- Use the
ALTER VIEW ... RENAME TO
statement to rename a view. - Use the
ALTER VIEW ... (SET check_option)
statement to change the check option of a view. - Use the
ALTER VIEW ... SET SCHEMA
statement to change the schema of a view.