Terminology used in this document reflects the stored object hierarchy:
-
Stored routines include stored procedures(L1-1-1) and functions(L1-1-2).
-
Stored programs include stored routines(L1-1), triggers(L1-2), and events(L1-3).
-
Stored objects include stored programs(L1) and views(L1).
Each stored program contains a body that consists of an SQL statement. This statement may be a compound statement made up of several statements separated by semicolon (;
) characters. For example, the following stored procedure has a body made up of a BEGIN ... END
block that contains a SET
statement and a REPEAT
loop that itself contains another SET
statement:
CREATE PROCEDURE dorepeat(p1 INT) BEGIN SET @x = 0; REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT; END;
#for mysql client#
If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.
To redefine the mysql delimiter, use the delimiter
command. The following example shows how to do this for the dorepeat()
procedure just shown. The delimiter is changed to //
to enable the entire definition to be passed to the server as a single statement, and then restored to ;
before invoking the procedure. This enables the ;
delimiter used in the procedure body to be passed through to the server rather than being interpreted by mysql itself.
mysql>delimiter //
mysql>CREATE PROCEDURE dorepeat(p1 INT)
->BEGIN
->SET @x = 0;
->REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT;
->END
->//
Query OK, 0 rows affected (0.00 sec) mysql>delimiter ;
mysql>CALL dorepeat(1000);
Query OK, 0 rows affected (0.00 sec) mysql>SELECT @x;
+------+ | @x | +------+ | 1001 | +------+ 1 row in set (0.00 sec)
You can redefine the delimiter to a string other than //
, and the delimiter can consist of a single character or multiple characters. You should avoid the use of the backslash () character because that is the escape character for MySQL.
The following is an example of a function that takes a parameter, performs an operation using an SQL function, and returns the result. In this case, it is unnecessary to use delimiter
because the function definition contains no internal ;
statement delimiters:
mysql>CREATE FUNCTION hello (s CHAR(20))
mysql>RETURNS CHAR(50) DETERMINISTIC
->RETURN CONCAT('Hello, ',s,'!');
Query OK, 0 rows affected (0.00 sec) mysql>SELECT hello('world');
+----------------+ | hello('world') | +----------------+ | Hello, world! | +----------------+ 1 row in set (0.00 sec)
#for mysql client#
Stored programs (procedures, functions, triggers, and events) and views are defined prior to use and, when referenced, execute within a security context that determines their privileges. These privileges are controlled by their DEFINER
attribute and SQL SECURITY
characteristic.
All stored object definitions can include a DEFINER
attribute that names a MySQL account. If a definition omits the DEFINER
attribute, the default definer is the user who creates the object.
MySQL uses the following rules to control which accounts a user can specify in an object DEFINER
attribute:
-
If you have the
SUPER
privilege, you can specify any account as theDEFINER
value, although a warning is generated if the account does not exist. -
Otherwise, the only permitted account is your own, either specified literally or as
CURRENT_USER
orCURRENT_USER()
. You cannot set the definer to some other account.
Creating a stored object with a nonexistent DEFINER
account may have negative consequences:
-
For a stored routine, an error occurs at routine execution time if the
SQL SECURITY
value isDEFINER
but the definer account does not exist. -
For a trigger, it is not a good idea for trigger activation to occur until the account actually does exist. Otherwise, the behavior with respect to privilege checking is undefined.
-
For an event, an error occurs at event execution time if the account does not exist.
-
For a view, an error occurs when the view is referenced if the
SQL SECURITY
value isDEFINER
but the definer account does not exist.
Definitions for stored routines (procedures and functions) and views can include an SQL SECURITY
characteristic with a value of DEFINER
or INVOKER
to specify whether the object executes in definer or invoker context. If a definition omits the SQL SECURITY
characteristic, the default is definer context.
Triggers and events have no SQL SECURITY
characteristic and always execute in definer context. The server invokes these objects automatically as necessary, so there is no invoking user.
Definer and invoker security contexts differ as follows:
-
A stored object that executes in definer security context executes with the privileges of the account named by its
DEFINER
attribute. These privileges may be entirely different from those of the invoking user. The invoker must have appropriate privileges to reference the object (for example,EXECUTE
to call a stored procedure orSELECT
to select from a view), but during object execution, the invoker's privileges are ignored and only theDEFINER
account privileges matter. If theDEFINER
account has few privileges, the object is correspondingly limited in the operations it can perform. If theDEFINER
account is highly privileged (such as aroot
account), the object can perform powerful operations no matter who invokes it. -
A stored routine or view that executes in invoker security context can perform only operations for which the invoker has privileges. The
DEFINER
attribute has no effect during object execution.
Consider the following stored procedure, which is declared with SQL SECURITY DEFINER
to execute in definer security context:
CREATE DEFINER = 'admin'@'localhost' PROCEDURE p1() SQL SECURITY DEFINER BEGIN UPDATE t1 SET counter = counter + 1; END;
Any user who has the EXECUTE
privilege for p1
can invoke it with a CALL
statement. However, when p1
executes, it does so in definer security context and thus executes with the privileges of 'admin'@'localhost'
, the account named in the DEFINER
attribute. This account must have the EXECUTE
privilege for p1
as well as the UPDATE
privilege for the table t1
referenced within the object body. Otherwise, the procedure fails.
Now consider this stored procedure, which is identical to p1
except that its SQL SECURITY
characteristic is INVOKER
:
CREATE DEFINER = 'admin'@'localhost' PROCEDURE p2() SQL SECURITY INVOKER BEGIN UPDATE t1 SET counter = counter + 1; END;
Unlike p1
, p2
executes in invoker security context and thus with the privileges of the invoking user regardless of the DEFINER
attribute value. p2
fails if the invoker lacks the EXECUTE
privilege for p2
or the UPDATE
privilege for the table t1
.
To minimize the risk potential for stored object creation and use, follow these guidelines:
-
For a stored routine or view, use
SQL SECURITY INVOKER
in the object definition when possible so that it can be used only by users with permissions appropriate for the operations performed by the object. -
If you create definer-context stored objects while using an account that has the
SUPER
privilege, specify an explicitDEFINER
attribute that names an account possessing only the privileges required for the operations performed by the object. Specify a highly privilegedDEFINER
account only when absolutely necessary. -
Administrators can prevent users from creating stored objects that specify highly privileged
DEFINER
accounts by not granting them theSUPER
privilege. -
Definer-context objects should be written keeping in mind that they may be able to access data for which the invoking user has no privileges. In some cases, you can prevent references to these objects by not granting unauthorized users particular privileges:
However, no such control exists for triggers and events because they always execute in definer context. The server invokes these objects automatically as necessary; users do not reference them directly:
-
A trigger is activated by access to the table with which it is associated, even ordinary table accesses by users with no special privileges.
-
An event is executed by the server on a scheduled basis.
In both cases, if the
DEFINER
account is highly privileged, the object may be able to perform sensitive or dangerous operations. This remains true if the privileges needed to create the object are revoked from the account of the user who created it. Administrators should be especially careful about granting users object-creation privileges. -
23.8 Restrictions on Stored Programs
These restrictions apply to the features described in Chapter 23, Stored Objects.
Some of the restrictions noted here apply to all stored routines; that is, both to stored procedures and stored functions. There are also some restrictions specific to stored functions but not to stored procedures.
The restrictions for stored functions also apply to triggers. There are also some restrictions specific to triggers.
The restrictions for stored procedures also apply to the DO
clause of Event Scheduler event definitions. There are also some restrictions specific to events.
Stored routines cannot contain arbitrary SQL statements. The following statements are not permitted:
-
The locking statements
LOCK TABLES
andUNLOCK TABLES
. -
LOAD DATA
andLOAD TABLE
. -
SQL prepared statements (
PREPARE
,EXECUTE
,DEALLOCATE PREPARE
) can be used in stored procedures, but not stored functions or triggers. Thus, stored functions and triggers cannot use dynamic SQL (where you construct statements as strings and then execute them). -
Generally, statements not permitted in SQL prepared statements are also not permitted in stored programs. For a list of statements supported as prepared statements, see Section 13.5, “Prepared Statements”. Exceptions are
SIGNAL
,RESIGNAL
, andGET DIAGNOSTICS
, which are not permissible as prepared statements but are permitted in stored programs. -
Because local variables are in scope only during stored program execution, references to them are not permitted in prepared statements created within a stored program. Prepared statement scope is the current session, not the stored program, so the statement could be executed after the program ends, at which point the variables would no longer be in scope. For example,
SELECT ... INTO
cannot be used as a prepared statement. This restriction also applies to stored procedure and function parameters. See Section 13.5.1, “PREPARE Statement”.local_var
-
Within all stored programs (stored procedures and functions, triggers, and events), the parser treats
BEGIN [WORK]
as the beginning of aBEGIN ... END
block. To begin a transaction in this context, useSTART TRANSACTION
instead.
The following additional statements or operations are not permitted within stored functions. They are permitted within stored procedures, except stored procedures that are invoked from within a stored function or trigger. For example, if you use FLUSH
in a stored procedure, that stored procedure cannot be called from a stored function or trigger.
-
Statements that perform explicit or implicit commit or rollback. Support for these statements is not required by the SQL standard, which states that each DBMS vendor may decide whether to permit them.
-
Statements that return a result set. This includes
SELECT
statements that do not have anINTO
clause and other statements such asvar_list
SHOW
,EXPLAIN
, andCHECK TABLE
. A function can process a result set either withSELECT ... INTO
or by using a cursor andvar_list
FETCH
statements. See Section 13.2.9.1, “SELECT ... INTO Statement”, and Section 13.6.6, “Cursors”. -
FLUSH
statements. -
Stored functions cannot be used recursively.
-
A stored function or trigger cannot modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.
-
If you refer to a temporary table multiple times in a stored function under different aliases, a
Can't reopen table: '
error occurs, even if the references occur in different statements within the function.tbl_name
'
-
HANDLER ... READ
statements that invoke stored functions can cause replication errors and are disallowed.
For triggers, the following additional restrictions apply:
-
Triggers are not activated by foreign key actions.
-
When using row-based replication, triggers on the slave are not activated by statements originating on the master. The triggers on the slave are activated when using statement-based replication. For more information, see Section 16.4.1.34, “Replication and Triggers”.
-
The
RETURN
statement is not permitted in triggers, which cannot return a value. To exit a trigger immediately, use theLEAVE
statement. -
Triggers are not permitted on tables in the
mysql
database. Nor are they permitted onINFORMATION_SCHEMA
orperformance_schema
tables. Those tables are actually views and triggers are not permitted on views. -
The trigger cache does not detect when metadata of the underlying objects has changed. If a trigger uses a table and the table has changed since the trigger was loaded into the cache, the trigger operates using the outdated metadata.
The same identifier might be used for a routine parameter, a local variable, and a table column. Also, the same local variable name can be used in nested blocks. For example:
CREATE PROCEDURE p (i INT) BEGIN DECLARE i INT DEFAULT 0; SELECT i FROM t; BEGIN DECLARE i INT DEFAULT 1; SELECT i FROM t; END; END;
In such cases, the identifier is ambiguous and the following precedence rules apply:
-
A local variable takes precedence over a routine parameter or table column.
-
A routine parameter takes precedence over a table column.
-
A local variable in an inner block takes precedence over a local variable in an outer block.
The behavior that variables take precedence over table columns is nonstandard.
Use of stored routines can cause replication problems. This issue is discussed further in Section 23.7, “Stored Program Binary Logging”.
The --replicate-wild-do-table=
option applies to tables, views, and triggers. It does not apply to stored procedures and functions, or events. To filter statements operating on the latter objects, use one or more of the db_name.tbl_name
--replicate-*-db
options.
The MySQL stored routine syntax is based on the SQL:2003 standard. The following items from that standard are not currently supported:
-
UNDO
handlers -
FOR
loops
To prevent problems of interaction between sessions, when a client issues a statement, the server uses a snapshot of routines and triggers available for execution of the statement. That is, the server calculates a list of procedures, functions, and triggers that may be used during execution of the statement, loads them, and then proceeds to execute the statement. While the statement executes, it does not see changes to routines performed by other sessions.
For maximum concurrency, stored functions should minimize their side-effects; in particular, updating a table within a stored function can reduce concurrent operations on that table. A stored function acquires table locks before executing, to avoid inconsistency in the binary log due to mismatch of the order in which statements execute and when they appear in the log. When statement-based binary logging is used, statements that invoke a function are recorded rather than the statements executed within the function. Consequently, stored functions that update the same underlying tables do not execute in parallel. In contrast, stored procedures do not acquire table-level locks. All statements executed within stored procedures are written to the binary log, even for statement-based binary logging. See Section 23.7, “Stored Program Binary Logging”.
The following limitations are specific to the Event Scheduler:
-
Event names are handled in case-insensitive fashion. For example, you cannot have two events in the same database with the names
anEvent
andAnEvent
. -
An event may not be created, altered, or dropped from within a stored program, if the event name is specified by means of a variable. An event also may not create, alter, or drop stored routines or triggers.
-
DDL statements on events are prohibited while a
LOCK TABLES
statement is in effect. -
Event timings using the intervals
YEAR
,QUARTER
,MONTH
, andYEAR_MONTH
are resolved in months; those using any other interval are resolved in seconds. There is no way to cause events scheduled to occur at the same second to execute in a given order. In addition—due to rounding, the nature of threaded applications, and the fact that a nonzero length of time is required to create events and to signal their execution—events may be delayed by as much as 1 or 2 seconds. However, the time shown in theINFORMATION_SCHEMA.EVENTS
table'sLAST_EXECUTED
column or themysql.event
table'slast_executed
column is always accurate to within one second of the actual event execution time. (See also Bug #16522.) -
Each execution of the statements contained in the body of an event takes place in a new connection; thus, these statements has no effect in a given user session on the server's statement counts such as
Com_select
andCom_insert
that are displayed bySHOW STATUS
. However, such counts are updated in the global scope. (Bug #16422) -
Events do not support times later than the end of the Unix Epoch; this is approximately the beginning of the year 2038. Such dates are specifically not permitted by the Event Scheduler. (Bug #16396)
-
References to stored functions, user-defined functions, and tables in the
ON SCHEDULE
clauses ofCREATE EVENT
andALTER EVENT
statements are not supported. These sorts of references are not permitted. (See Bug #22830 for more information.)
Stored routines and triggers in NDB Cluster. Stored procedures, stored functions, and triggers are all supported by tables using the NDB
storage engine; however, it is important to keep in mind that they do not propagate automatically between MySQL Servers acting as Cluster SQL nodes. This is because of the following:
-
Stored routine definitions are kept in tables in the
mysql
system database using theMyISAM
storage engine, and so do not participate in clustering. -
The
.TRN
and.TRG
files containing trigger definitions are not read by theNDB
storage engine, and are not copied between Cluster nodes.
Any stored routine or trigger that interacts with NDB Cluster tables must be re-created by running the appropriate CREATE PROCEDURE
, CREATE FUNCTION
, or CREATE TRIGGER
statements on each MySQL Server that participates in the cluster where you wish to use the stored routine or trigger. Similarly, any changes to existing stored routines or triggers must be carried out explicitly on all Cluster SQL nodes, using the appropriate ALTER
or DROP
statements on each MySQL Server accessing the cluster.
Do not attempt to work around the issue described in the first item mentioned previously by converting any mysql
database tables to use the NDB
storage engine. Altering the system tables in the mysql
database is not supported and is very likely to produce undesirable results.
The maximum number of tables that can be referenced in the definition of a view is 61.
View processing is not optimized:
-
It is not possible to create an index on a view.
-
Indexes can be used for views processed using the merge algorithm. However, a view that is processed with the temptable algorithm is unable to take advantage of indexes on its underlying tables (although indexes can be used during generation of the temporary tables).
Before MySQL 5.7.7, subqueries cannot be used in the FROM
clause of a view.
There is a general principle that you cannot modify a table and select from the same table in a subquery. See Section 13.2.10.12, “Restrictions on Subqueries”.
The same principle also applies if you select from a view that selects from the table, if the view selects from the table in a subquery and the view is evaluated using the merge algorithm. Example:
CREATE VIEW v1 AS SELECT * FROM t2 WHERE EXISTS (SELECT 1 FROM t1 WHERE t1.a = t2.a); UPDATE t1, v2 SET t1.a = 1 WHERE t1.b = v2.b;
If the view is evaluated using a temporary table, you can select from the table in the view subquery and still modify that table in the outer query. In this case the view will be stored in a temporary table and thus you are not really selecting from the table in a subquery and modifying it “at the same time.” (This is another reason you might wish to force MySQL to use the temptable algorithm by specifying ALGORITHM = TEMPTABLE
in the view definition.)
You can use DROP TABLE
or ALTER TABLE
to drop or alter a table that is used in a view definition. No warning results from the DROP
or ALTER
operation, even though this invalidates the view. Instead, an error occurs later, when the view is used. CHECK TABLE
can be used to check for views that have been invalidated by DROP
or ALTER
operations.
With regard to view updatability, the overall goal for views is that if any view is theoretically updatable, it should be updatable in practice. MySQL as quickly as possible. Many theoretically updatable views can be updated now, but limitations still exist. For details, see Section 23.5.3, “Updatable and Insertable Views”.
There exists a shortcoming with the current implementation of views. If a user is granted the basic privileges necessary to create a view (the CREATE VIEW
and SELECT
privileges), that user will be unable to call SHOW CREATE VIEW
on that object unless the user is also granted the SHOW VIEW
privilege.
That shortcoming can lead to problems backing up a database with mysqldump, which may fail due to insufficient privileges. This problem is described in Bug #22062.
The workaround to the problem is for the administrator to manually grant the SHOW VIEW
privilege to users who are granted CREATE VIEW
, since MySQL doesn't grant it implicitly when views are created.
Views do not have indexes, so index hints do not apply. Use of index hints when selecting from a view is not permitted.
SHOW CREATE VIEW
displays view definitions using an AS
clause for each column. If a column is created from an expression, the default alias is the expression text, which can be quite long. Aliases for column names in alias_name
CREATE VIEW
statements are checked against the maximum column length of 64 characters (not the maximum alias length of 256 characters). As a result, views created from the output of SHOW CREATE VIEW
fail if any column alias exceeds 64 characters. This can cause problems in the following circumstances for views with too-long aliases:
-
View definitions fail to replicate to newer slaves that enforce the column-length restriction.
-
Dump files created with mysqldump cannot be loaded into servers that enforce the column-length restriction.
A workaround for either problem is to modify each problematic view definition to use aliases that provide shorter column names. Then the view will replicate properly, and can be dumped and reloaded without causing an error. To modify the definition, drop and create the view again with DROP VIEW
and CREATE VIEW
, or replace the definition with CREATE OR REPLACE VIEW
.
For problems that occur when reloading view definitions in dump files, another workaround is to edit the dump file to modify its CREATE VIEW
statements. However, this does not change the original view definitions, which may cause problems for subsequent dump operations.