19.2 Using Stored Routines (Procedures and Functions)

19.2.1 Stored Routine Syntax
19.2.2 Stored Routines and MySQL Privileges
19.2.3 Stored Routine Metadata
19.2.4 Stored Procedures, Functions, Triggers, and LAST_INSERT_ID()

Stored routines (procedures and functions) are supported in MySQL 5.5. A stored routine is a set of SQL statements that can be stored in the server. Once this has been done, clients don't need to keep reissuing the individual statements but can refer to the stored routine instead.

Stored routines require the proc table in the mysql database. This table is created during the MySQL 5.5 installation procedure. If you are upgrading to MySQL 5.5 from an earlier version, be sure to update your grant tables to make sure that the proc table exists. See Section 4.4.7, “mysql_upgrade — Check and Upgrade MySQL Tables”.

Stored routines can be particularly useful in certain situations:

Stored routines can provide improved performance because less information needs to be sent between the server and the client. The tradeoff is that this does increase the load on the database server because more of the work is done on the server side and less is done on the client (application) side. Consider this if many client machines (such as Web servers) are serviced by only one or a few database servers.

Stored routines also enable you to have libraries of functions in the database server. This is a feature shared by modern application languages that enable such design internally (for example, by using classes). Using these client application language features is beneficial for the programmer even outside the scope of database use.

MySQL follows the SQL:2003 syntax for stored routines, which is also used by IBM's DB2. All syntax described here is supported and any limitations and extensions are documented where appropriate.

Additional Resources