[SQL must know and know] - Lesson 18 Using Views

Table of contents

18.1 Views

        18.1.1 Why use views

        18.1.2 Rules and restrictions for views

18.2 Creating Views

        view rename

        18.2.1 Using Views to Simplify Complex Joins

        Create reusable views

        18.2.2 Reformatting retrieved data with views

        18.2.3 Filtering unwanted data with views

        WHERE clause vs. WHERE clause

        18.2.4 Using Views and Calculated Fields

18.3 Summary


        This lesson explains what views are, how they work, when to use them, and how views can be used to simplify some of the SQL operations performed in previous lessons.

18.1 Views

        Views are virtual tables . Unlike tables that contain data, views contain only queries that dynamically retrieve data when used.

        As a view, it does not contain any columns or data, but a query.


        18.1.1 Why use views

        Here are some common applications of views:

  • Reuse SQL statements. (this is the most important role)
  • Simplify complex SQL operations. After a query is written, it can be easily reused without knowing its underlying query details.
  • Use part of the table instead of the whole table.
  • Protect data. Users can be granted access to specific parts of a table rather than to the entire table.
  • Change data format and presentation. Views can return data in a different representation and format than the underlying table.

        After views are created, they can be used in much the same way as tables. You can perform SELECT operations on views, filter and sort data, join views to other views or tables, and even add and update data (there are certain restrictions on adding and updating data, which will be described later).

        It is important to understand that a view is merely a facility for viewing data stored elsewhere. Views themselves contain no data, so the data returned is retrieved from other tables. When adding or changing data in these tables, the view will return the changed data.

        Frequently used SQL statements can be created as views for later use.

        For the company level , a team usually has a database, and too many views will lead to confusion. It is recommended to discuss with the team members to determine the content of the view.

        For personal use , you can use your own mind, but it is also recommended to use a reasonable name so that you can understand what the view does in the future, that is, the so-called "knowing the name" .


        18.1.2 Rules and restrictions for views

        Below are some of the most common rules and restrictions regarding view creation and use. Like tables, views must be uniquely named (you cannot give a view the same name as another view or table).

  • There is no limit to the number of views that can be created.
  • To create a view, you must have sufficient access rights. These permissions are usually granted by the database administrator.
  • Views can be nested , that is, they can be constructed from queries that retrieve data from other views. The number of levels of nesting allowed varies in different DBMSs ( nested views can severely degrade query performance , so they should be thoroughly tested before being used in a production environment).
  • Many DBMSs prohibit the use of an ORDER BY clause in view queries.
  • Some DBMSs require that all columns returned be named, and if the column is a computed field, an alias is required (see Lesson 7 for more information on column aliases).
  • Views cannot be indexed, and cannot have associated triggers or defaults.
  • Some DBMSs treat views as read-only queries, which means that data can be retrieved from the view, but cannot be written back to the underlying table. See your specific DBMS documentation for details.
  • Some DBMSs allow the creation of views that cannot be inserted or updated so that rows no longer belong to the view. For example, have a view that retrieves only customers with email addresses. If you update a customer, removing his email address, that customer will no longer be part of the view. This is the default behavior and is allowed, but some DBMSs may prevent this from happening.

18.2 Creating Views

        Views are created with the CREATE VIEW statement. Like CREATE TABLE, CREATE VIEW can only be used to create views that do not exist.


        view rename

        To delete a view, you can use the DROP statement, whose syntax is

DROP VIEW viewname;

        To overwrite (or update) a view, it must be dropped and then recreated.


        18.2.1 Using Views to Simplify Complex Joins

        One of the most common applications of views is to hide complex SQL, which usually involves joins.

CREATE VIEW ProductCustomers AS
SELECT cust_name, cust_contact, prod_id
FROM Customers, Orders, OrderItems
WHERE Customers.cust_id = Orders.cust_id
AND OrderItems.order_num = Orders.order_num;

        This statement creates a view called ProductCustomers that joins the three tables to return a list of all customers who have ordered any product. If you execute SELECT * FROMProductCustomers, the customers who ordered any product will be listed.

        Retrieving the customers who ordered the product RGAN01 can be done as follows:

SELECT cust_name, cust_contact
FROM ProductCustomers
WHERE prod_id = 'RGAN01';

        This statement retrieves specific data from the view through the WHERE clause. When the DBMS processes this query, it adds the specified WHERE clause to the existing WHERE clause in the view query so that the data is filtered correctly.

        It can be seen that views greatly simplify the use of complex SQL statements. With views, the underlying SQL can be written once and then used as many times as needed.


        Create reusable views

        It is a good idea to create views that are not bound to specific data. For example, the view created above returns customers who ordered all products, not just RGAN01 (this view was created first). Extending the scope of a view not only makes it reusable, but potentially more useful. Doing so eliminates the need to create and maintain multiple similar views.


        18.2.2 Reformatting retrieved data with views

        As mentioned earlier, another common use of views is to reformat retrieved data.

SELECT RTRIM(vend_name) + ' (' + RTRIM(vend_country) + ')' AS vend_title
FROM Vendors ORDER BY vend_name;

        Here is the same statement, but using the || syntax (as explained in Lesson 7):

SELECT RTRIM(vend_name) || ' (' || RTRIM(vend_country) || ')' AS vend_title
FROM Vendors ORDER BY vend_name;

        Now, suppose that results in this format are often required. Instead of performing this stitching every time we need it, we create a view and use it. To convert this statement into a view, proceed as follows:

CREATE VIEW VendorLocations AS
SELECT RTRIM(vend_name) + ' (' + RTRIM(vend_country) + ')'
AS vend_title
FROM Vendors;

        Here is the same statement using the || syntax:

CREATE VIEW VendorLocations AS
SELECT RTRIM(vend_name) || ' (' || RTRIM(vend_country) || ')' AS vend_title
FROM Vendors;

        This statement creates a view using the same query as the previous SELECT statement. To retrieve data, create all mailing tags, proceed as follows:

SELECT * FROM VendorLocations;

        18.2.3 Filtering unwanted data with views

        Views are also useful for applying ordinary WHERE clauses.

CREATE VIEW CustomerEMailList AS
SELECT cust_id, cust_name, cust_email
FROM Customers
WHERE cust_email IS NOT NULL;

        Now, the view CustomerEMailList can be used like any other table.

SELECT * FROM CustomerEMailList;

        WHERE clause vs. WHERE clause

        If a WHERE clause is used when retrieving data from a view, the two sets of clauses (one in the view and one passed to the view) are automatically combined.

        It sounds a bit of a mouthful, but in fact there is a where in the view and a layer of where outside the view.

        I feel like this is also understandable:

        First, query the data in the view, and then filter the found data in where outside the view. Whether the specific implementation is so unclear, the above is just my intuitive feeling.


        18.2.4 Using Views and Calculated Fields

        Views are also particularly useful for simplifying the use of calculated fields.

SELECT prod_id, quantity, item_price, quantity*item_price AS expanded_price
FROM OrderItems
WHERE order_num = 20008;

        To convert it to a view, proceed as follows:

CREATE VIEW OrderItemsExpanded AS
SELECT order_num,prod_id,quantity,item_price,quantity*item_price AS expanded_price
FROM OrderItems;

        To retrieve the details of order 20008 (the output above), proceed as follows:

SELECT * FROM OrderItemsExpanded WHERE order_num = 20008;

        As you can see, views are very easy to create and easy to use. Used correctly, views can greatly simplify working with complex data.


18.3 Summary

        Views are virtual tables. Instead of data, they contain queries that retrieve data on demand. Views provide a level of encapsulation of SELECT statements that can be used to simplify data manipulation, reformat, or protect underlying data.

Guess you like

Origin blog.csdn.net/qq_57163366/article/details/130222967