PostgreSQL View
A View is a fake table, except that it is a PostgreSQL statement stored in the database under a related name.
A View is actually a combination of tables in the form of a predefined PostgreSQL query.
A View can contain all rows of a table or selected rows from one or more tables.
A View can be created from one or more tables, depending on the PostgreSQL query used to create the view.
A View is a virtual table that allows users to achieve the following:
- A more natural or intuitive way for users or user groups to look up structured data.
- Restrict data access, so users can only see limited data rather than the complete table.
- Aggregate data from various tables to generate reports.
PostgreSQL views are read-only, so it may not be possible to execute DELETE, INSERT, or UPDATE statements on a view. However, you can create a trigger on a view that fires when a DELETE, INSERT, or UPDATE is attempted on it, with the actions to be performed defined in the trigger body.
CREATE VIEW (create view)
In PostgreSQL, views are created with the CREATE VIEW statement. A view can be created from one table, multiple tables, or other views.
The basic syntax of CREATE VIEW is as follows:
CREATE [TEMP | TEMPORARY] VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in a SELECT statement, much the same way as in a normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is used, the view will be created in a temporary database.
Example
Create the COMPANY table (Download the COMPANY SQL file ), with the following data:
runoobdb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
Now, here is an example of creating a view from the COMPANY table. The view selects only a few columns from the COMPANY table:
runoobdb=# CREATE VIEW COMPANY_VIEW AS
SELECT ID, NAME, AGE
FROM COMPANY;
Now you can query COMPANY_VIEW in the same way you would query an actual table. Here is an example:
runoobdb# SELECT * FROM COMPANY_VIEW;
The result is as follows:
id | name | age
----+-------+-----
1 | Paul | 32
2 | Allen | 25
3 | Teddy | 23
4 | Mark | 25
5 | David | 27
6 | Kim | 22
7 | James | 24
(7 rows)
DROP VIEW (drop view)
To drop a view, simply use the DROP VIEW statement with view_name. The basic syntax of DROP VIEW is as follows:
runoobdb=# DROP VIEW view_name;
The following command will drop the COMPANY_VIEW view we created earlier:
runoobdb=# DROP VIEW COMPANY_VIEW;