The following example uses the CREATE VIEW statement to create a view based on the customer table:
Output:
The following query data from the contact view:
Output:
2) Using the CREATE VIEW statement to create a view based on a complex query
The following example creates a view based on the tables customer, address, city, and country:
The following query retrieves data from the customer_info view:
Output:
3) Creating a view based on another view
The following statement creates a view called customer_usa based on the customer_info view. The customer_usa returns the customers who are in the United States:
Here’s the query that retrieves data from the customer_usa view:
Output:
Replacing a view
To change the defining query of a view, you use the CREATE OR REPLACE VIEW statement:
In this syntax, you add the OR REPLACE between the CREATE and VIEW keywords. If the view already exists, the statement replaces the existing view; otherwise, it creates a new view.
For example, the following statement changes the defining query of the contact view to include the phone information from the address table:
Display a view on psql
To display a view on psql, you follow these steps:
First, open the Command Prompt on Windows or Terminal on Unix-like systems and connect to the PostgreSQL server:
Second, change the current database to dvdrental:
Third, display the view information using the \d+ view_name command. For example, the following shows the contact view:
Output:
Summary
Use the PostgreSQL CREATE VIEW statement to create a new view in your database.
Use the \d+ command in psql to display the information of a view.