19.2. CREATE VIEW Syntax

MySQL 5.0

19.2. CREATE VIEW Syntax

CREATE
    [OR REPLACE]
    [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
    [DEFINER = {  | CURRENT_USER }]
    [SQL SECURITY { DEFINER | INVOKER }]
    VIEW  [()]
    AS 
    [WITH [CASCADED | LOCAL] CHECK OPTION]

This statement creates a new view, or replaces an existing one if the clause is given. The is a statement that provides the definition of the view. The statement can select from base tables or other views.

This statement requires the privilege for the view, and some privilege for each column selected by the statement. For columns used elsewhere in the statement you must have the privilege. If the clause is present, you must also have the privilege for the view.

A view belongs to a database. By default, a new view is created in the default database. To create the view explicitly in a given database, specify the name as when you create it.

mysql> 

Base tables and views share the same namespace within a database, so a database cannot contain a base table and a view that have the same name.

Views must have unique column names with no duplicates, just like base tables. By default, the names of the columns retrieved by the statement are used for the view column names. To define explicit names for the view columns, the optional clause can be given as a list of comma-separated identifiers. The number of names in must be the same as the number of columns retrieved by the statement.

Columns retrieved by the statement can be simple references to table columns. They can also be expressions that use functions, constant values, operators, and so forth.

Unqualified table or view names in the statement are interpreted with respect to the default database. A view can refer to tables or views in other databases by qualifying the table or view name with the proper database name.

A view can be created from many kinds of statements. It can refer to base tables or other views. It can use joins, , and subqueries. The need not even refer to any tables. The following example defines a view that selects two columns from another table, as well as an expression calculated from those columns:

mysql> 
mysql> 
mysql> 
mysql> 
+------+-------+-------+
| qty  | price | value |
+------+-------+-------+
|    3 |    50 |   150 |
+------+-------+-------+

A view definition is subject to the following restrictions:

  • The statement cannot contain a subquery in the clause.

  • The statement cannot refer to system or user variables.

  • The statement cannot refer to prepared statement parameters.

  • Within a stored routine, the definition cannot refer to routine parameters or local variables.

  • Any table or view referred to in the definition must exist. However, after a view has been created, it is possible to drop a table or view that the definition refers to. In this case, use of the view results in an error. To check a view definition for problems of this kind, use the statement.

  • The definition cannot refer to a table, and you cannot create a view.

  • The tables named in the view definition must already exist.

  • You cannot associate a trigger with a view.

is allowed in a view definition, but it is ignored if you select from a view using a statement that has its own .

For other options or clauses in the definition, they are added to the options or clauses of the statement that references the view, but the effect is undefined. For example, if a view definition includes a clause, and you select from the view using a statement that has its own clause, it is undefined which limit applies. This same principle applies to options such as , , or that follow the keyword, and to clauses such as , , , and .

If you create a view and then change the query processing environment by changing system variables, that may affect the results that you get from the view:

mysql> 
Query OK, 0 rows affected (0.00 sec)

mysql> 
Query OK, 0 rows affected (0.00 sec)

mysql> 
+-------------------+---------------------+
| CHARSET(CHAR(65)) | COLLATION(CHAR(65)) |
+-------------------+---------------------+
| latin1            | latin1_swedish_ci   |
+-------------------+---------------------+
1 row in set (0.00 sec)

mysql> 
Query OK, 0 rows affected (0.00 sec)

mysql> 
+-------------------+---------------------+
| CHARSET(CHAR(65)) | COLLATION(CHAR(65)) |
+-------------------+---------------------+
| utf8              | utf8_general_ci     |
+-------------------+---------------------+
1 row in set (0.00 sec)

The and clauses specify the security context to be used when checking access privileges at view invocation time. They were addded in MySQL 5.0.13, but have no effect until MySQL 5.0.16.

also can be given as .

Within a stored routine that is defined with the characteristic, returns the routine creator. This also affects a view defined within such a routine, if the view definition contains a value of .

The default value is the user who executes the statement. (This is the same as .) If a value is given, it should be a MySQL account in '@'' format (the same format used in the statement). The and values both are required.

If you specify the clause, you cannot set the value to any user but your own unless you have the privilege. These rules determine the legal user values:

  • If you do not have the privilege, the only legal value is your own account, either specified literally or by using . You cannot set the definer to some other account.

  • If you have the privilege, you can specify any syntactically legal account name. If the account does not actually exist, a warning is generated.

The characteristic determines which MySQL account to use when checking access privileges for the view when the view is executed. The legal characteristic values are and . These indicate that the view must be executable by the user who defined it or invoked it, respectively. The default value is .

As of MySQL 5.0.16 (when the and clauses were implemented), view privileges are checked like this:

  • At view definition time, the view creator must have the privileges needed to use the top-level objects accessed by the view. For example, if the view definition refers to a stored function, only the privileges needed to invoke the function can be checked. The privileges required when the function runs can be checked only as it executes: For different invocations of the function, different execution paths within the function might be taken.

  • At view execution time, privileges for objects accessed by the view are checked against the privileges held by the view creator or invoker, depending on whether the characteristic is or , respectively.

  • If view execution causes execution of a stored function, privilege checking for statements executed within the function depend on whether the function is defined with a characteristic of or . If the security characteristic is , the function runs with the privileges of its creator. If the characteristic is , the function runs with the privileges determined by the view's characteristic.

Prior to MySQL 5.0.16 (before the and clauses were implemented), privileges required for objects used in a view are checked at view creation time.

Example: A view might depend on a stored function, and that function might invoke other stored routines. For example, the following view invokes a stored function :

CREATE VIEW v AS SELECT * FROM t WHERE t.id = f(t.name);

Suppose that contains a statement such as this:

IF name IS NULL then
  CALL p1();
ELSE
  CALL p2();
END IF;

The privileges required for executing statements within need to be checked when executes. This might mean that privileges are needed for or , depending on the execution path within . Those privileges need to be checked at runtime, and the user who must possess the privileges is determined by the values of the function and the view .

The and clauses for views are extensions to standard SQL. In standard SQL, views are handled using the rules for .

If you invoke a view that was created before MySQL 5.0.13, it is treated as though it was created with a clause and with a value that is the same as your account. However, because the actual definer is unknown, MySQL issues a warning. To make the warning go away, it is sufficient to re-create the view so that the view definition includes a clause.

The optional clause is a MySQL extension to standard SQL. takes three values: , , or . The default algorithm is if no clause is present. The algorithm affects how MySQL processes the view.

For , the text of a statement that refers to the view and the view definition are merged such that parts of the view definition replace corresponding parts of the statement.

For , the results from the view are retrieved into a temporary table, which then is used to execute the statement.

For , MySQL chooses which algorithm to use. It prefers over if possible, because is usually more efficient and because a view cannot be updatable if a temporary table is used.

A reason to choose explicitly is that locks can be released on underlying tables after the temporary table has been created and before it is used to finish processing the statement. This might result in quicker lock release than the algorithm so that other clients that use the view are not blocked as long.

A view algorithm can be for three reasons:

  • No clause is present in the statement.

  • The statement has an explicit clause.

  • is specified for a view that can be processed only with a temporary table. In this case, MySQL generates a warning and sets the algorithm to .

As mentioned earlier, is handled by merging corresponding parts of a view definition into the statement that refers to the view. The following examples briefly illustrate how the algorithm works. The examples assume that there is a view that has this definition:

CREATE ALGORITHM = MERGE VIEW v_merge (vc1, vc2) AS
SELECT c1, c2 FROM t WHERE c3 > 100;

Example 1: Suppose that we issue this statement:

SELECT * FROM v_merge;

MySQL handles the statement as follows:

  • becomes

  • becomes , which corresponds to

  • The view clause is added

The resulting statement to be executed becomes:

SELECT c1, c2 FROM t WHERE c3 > 100;

Example 2: Suppose that we issue this statement:

SELECT * FROM v_merge WHERE vc1 < 100;

This statement is handled similarly to the previous one, except that becomes and the view clause is added to the statement clause using an connective (and parentheses are added to make sure the parts of the clause are executed with correct precedence). The resulting statement to be executed becomes:

SELECT c1, c2 FROM t WHERE (c3 > 100) AND (c1 < 100);

Effectively, the statement to be executed has a clause of this form:

WHERE (select WHERE) AND (view WHERE)

The algorithm requires a one-to-one relationship between the rows in the view and the rows in the underlying table. If this relationship does not hold, a temporary table must be used instead. Lack of a one-to-one relationship occurs if the view contains any of a number of constructs:

  • Aggregate functions (, , , , and so forth)

  • or

  • Refers only to literal values (in this case, there is no underlying table)

Some views are updatable. That is, you can use them in statements such as , , or to update the contents of the underlying table. For a view to be updatable, there must be a one-to-one relationship between the rows in the view and the rows in the underlying table. There are also certain other constructs that make a view non-updatable. To be more specific, a view is not updatable if it contains any of the following:

  • Aggregate functions (, , , , and so forth)

  • or

  • Subquery in the select list

  • Join

  • Non-updatable view in the clause

  • A subquery in the clause that refers to a table in the clause

  • Refers only to literal values (in this case, there is no underlying table to update)

  • (use of a temporary table always makes a view non-updatable)

With respect to insertability (being updatable with statements), an updatable view is insertable if it also satisfies these additional requirements for the view columns:

  • There must be no duplicate view column names.

  • The view must contain all columns in the base table that do not have a default value.

  • The view columns must be simple column references and not derived columns. A derived column is one that is not a simple column reference but is derived from an expression. These are examples of derived columns:

    3.14159
    col1 + 3
    UPPER(col2)
    col3 / col4
    ()
    

A view that has a mix of simple column references and derived columns is not insertable, but it can be updatable if you update only those columns that are not derived. Consider this view:

CREATE VIEW v AS SELECT col1, 1 AS col2 FROM t;

This view is not insertable because is derived from an expression. But it is updatable if the update does not try to update . This update is allowable:

UPDATE v SET col1 = 0;

This update is not allowable because it attempts to update a derived column:

UPDATE v SET col2 = 0;

It is sometimes possible for a multiple-table view to be updatable, assuming that it can be processed with the algorithm. For this to work, the view must use an inner join (not an outer join or a ). Also, only a single table in the view definition can be updated, so the clause must name only columns from one of the tables in the view. Views that use are disallowed even though they might be theoretically updatable, because the implementation uses temporary tables to process them.

For a multiple-table updatable view, can work if it inserts into a single table. is not supported.

The clause can be given for an updatable view to prevent inserts or updates to rows except those for which the clause in the is true.

In a clause for an updatable view, the and keywords determine the scope of check testing when the view is defined in terms of another view. The keyword restricts the only to the view being defined. causes the checks for underlying views to be evaluated as well. When neither keyword is given, the default is . Consider the definitions for the following table and set of views:

mysql> 
mysql> 
    -> 
mysql> 
    -> 
mysql> 
    -> 

Here the and views are defined in terms of another view, . has a check option, so inserts are tested only against the check. has a check option, so inserts are tested not only against its own check, but against those of underlying views. The following statements illustrate these differences:

mysql> 
Query OK, 1 row affected (0.00 sec)
mysql> 
ERROR 1369 (HY000): CHECK OPTION failed 'test.v3'

The updatability of views may be affected by the value of the system variable. See Section 5.2.2, “Server System Variables”.

The statement was added in MySQL 5.0.1. The clause was implemented in MySQL 5.0.2.