Creating PostgreSQL Updatable Views
Summary: in this tutorial, you will learn how to create PostgreSQL updatable views used for modifying data in the underlying table.
Introduction to PostgreSQL updatable views
In PostgreSQL, a view is a named query stored in the database server. A view can be updatable if it meets certain conditions. This means that you can insert, update, or delete data from the underlying tables via the view.
A view is updatable when it meets the following conditions:
First, the defining query of the view must have exactly one entry in the FROM
clause, which can be a table or another updatable view.
Second, the defining query must not contain one of the following clauses at the top level:
Third, the selection list of the defining query must not contain any:
An updatable view may contain both updatable and non-updatable columns. If you attempt to modify a non-updatable column, PostgreSQL will raise an error.
When you execute a modification statement such as INSERT, UPDATE, or DELETE to an updatable view, PostgreSQL will convert this statement into the corresponding statement of the underlying table.
If you have a WHERE
condition in the defining query of a view, you still can update or delete the rows that are not visible through the view. However, if you want to avoid this, you can use the WITH CHECK OPTION
to define the view.
PostgreSQL updatable views examples
We’ll take some examples of creating updatable views.
Setting up a sample table
The following statements create a table called cities
and insert some rows into the table:
1) Creating an updatable view
First, create an updatable view called city_us
that includes cities in the US only:
Second, insert a new row into the cities
table via the city_us
view:
Third, retrieve data from cities
table:
Output:
Fourth, update the data in the cities table via the city_us view:
Fifth, verify the update:
Output:
Sixth, delete a row from the cities
table via the city_us
view:
Finally, verify the delete:
Output:
The row with id 21 has been deleted.
Summary
- A view can be updatable when its defining query meets certain conditions.