Updated on 2023-05-23 GMT+08:00

Creating and Managing Views

Background

If some columns in one or more tables in a database are frequently searched for, an administrator can define a view for these columns, and then users can directly access these columns in the view without entering search criteria.

A view is different from a basic table. It is only a virtual object rather than a physical one. A database only stores the definition of a view and does not store its data. The data is still stored in the original base table. If data in the base table changes, the data in the view changes accordingly. In this sense, a view is like a window through which users can know their interested data and data changes in the database. A view is triggered every time it is referenced.

Managing a View

  • Creating a view
    Run the following command to create MyView:
    1
    CREATE OR REPLACE VIEW MyView AS SELECT * FROM tpcds.web_returns WHERE trunc(wr_refunded_cash) > 10000;
    

    OR REPLACE in CREATE VIEW is optional. The parameter OR REPLACE is specified to redefine an existing view.

  • Query a view.
    Query the MyView view. Real-time data will be returned.
    1
    SELECT * FROM MyView;
    
  • Run the following command to query the views in the current user:
    1
    SELECT * FROM user_views;
    
  • Run the following command to query all views:
    1
    SELECT * FROM dba_views;
    
  • View details about a specified view.
    Run the following command to view details about the dba_users view:
    1
    2
    3
    4
    5
    6
    7
    8
    \d+ dba_users
                          View "PG_CATALOG.DBA_USERS"
      Column  |         Type          | Modifiers | Storage  | Description
    ----------+-----------------------+-----------+----------+-------------
     USERNAME | CHARACTER VARYING(64) |           | extended |
    View definition:
     SELECT PG_AUTHID.ROLNAME::CHARACTER VARYING(64) AS USERNAME
       FROM PG_AUTHID;
    
  • Rebuild a view.

    Run the following command to rebuild a view without entering a query statement:

    1
    ALTER VIEW MyView REBUILD;
    
  • Delete a view
    Run the following command to delete MyView:
    1
    DROP VIEW MyView;