Delimiters in SQL
Delimiters are used when we need to define the stored procedures as well as to create triggers. Default delimiter is semicolon.
Step 1: Create and insert a value in a database.
But, if we are considering multiple statements, then we need to use different delimiters like $$ or //. The delimiter is a type of function in SQL. Using another delimiter which is //, we will get an error like this:
Output:
Now, by default, we are getting an error. How to make this work? In place of semicolon being used as the default delimiter, we would like to use //. Is it possible in SQL?
Yes, it is possible. The Syntax for this is given below:
Query:
Output:
Now, in this case, there would be no output because in the delimiter statement we have written //, and then in the select statement we have used the delimiter $$. The delimiter in the delimiter statement as well as in the select statement should be the same to make it run.
Now we can also use the delimiter $$. The syntax is given below:
Query:
When we are writing SQL statements, we use the semicolon to separate two different statements like in the example below:
Query:
For Example, MySQL workbench uses the delimiter semicolon (;) to separate two statements and then execute each statement separately.
But, a stored procedure contains multiple statements segregated by a semicolon (;).
If we are using the MySQL client program to define a stored procedure that consists of semicolon characters, the program will not treat the whole stored procedure as a single statement, but as many statements.
The command which we can use to redefine the delimiter is:
The delimiter_character consists of a single character or multiple characters like for example: // or $$.
Once changing the delimiter, we can use the new delimiter to end a statement as shown below:
To change the delimiter to the default one, which is a semicolon (;), we can use the following statement:
Usually, a stored procedure contains multiple statements which are separated by semicolons. To compile the procedure as a single statement, we need to temporarily change the delimiter from semicolon (;) to another delimiter such as $$ or //:
Delimiters in MySQL
I often see people are using Delimiters. I tried myself to find out what are delimiters and what is their purpose. After 20 minutes of googling, I was not able to find an answer which satisfies me. So, my question is now: What are delimiters and when should I use them?
![]()
4 Answers 4
Delimiters other than the default ; are typically used when defining functions, stored procedures, and triggers wherein you must define multiple statements. You define a different delimiter like $$ which is used to define the end of the entire procedure, but inside it, individual statements are each terminated by ; . That way, when the code is run in the mysql client, the client can tell where the entire procedure ends and execute it as a unit rather than executing the individual statements inside.
Note that the DELIMITER keyword is a function of the command line mysql client (and some other clients) only and not a regular MySQL language feature. It won’t work if you tried to pass it through a programming language API to MySQL. Some other clients like PHPMyAdmin have other methods to specify a non-default delimiter.
Example:
Attempting to use DELIMITER with a client that doesn’t support it will cause it to be sent to the server, which will report a syntax error. For example, using PHP and MySQLi:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘DELIMITER $$’ at line 1
Delimiters in MySQL?
Delimiters can be used when you need to define the stored procedures, function as well as to create triggers. The default delimiter is semicolon.
You can change the delimiters to create procedures and so on. However, but if you are considering multiple statements, then you need to use different delimiters like $$ or //.
Here we have a table “GetRecordFromNow” wherein the following are the records −
The delimiter keyword is a type of function in MySQL client. Here is the demo of delimiter that calls the above table using delimiter −
Delimiter mysql что это
Table of Contents
This chapter discusses stored programs and views, which are database objects defined in terms of SQL code that is stored on the server for later execution.
Stored programs include these objects:
Stored routines, that is, stored procedures and functions. A stored procedure is invoked using the CALL statement. A procedure does not have a return value but can modify its parameters for later inspection by the caller. It can also generate result sets to be returned to the client program. A stored function is used much like a built-in function. you invoke it in an expression and it returns a value during expression evaluation.
Triggers. A trigger is a named database object that is associated with a table and that is activated when a particular event occurs for the table, such as an insert or update.
Views are stored queries that when referenced produce a result set. A view acts as a virtual table.
This chapter describes how to use stored programs and views. The following sections provide additional information about SQL syntax for statements related to these objects:
For each object type, there are CREATE , ALTER , and DROP statements that control which objects exist and how they are defined. See Section 12.1, “Data Definition Statements”.
The CALL statement is used to invoke stored procedures. See Section 12.2.1, “ CALL Syntax”.
Stored program definitions include a body that may use compound statements, loops, conditionals, and declared variables. See Section 12.7, “MySQL Compound-Statement Syntax”.
18.1. Defining Stored Programs
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:
If you use the mysql client program to define a stored program that contains the semicolon characters within its definition, a problem arises. By default, mysql itself recognizes 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.
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:
18.2. Using Stored Routines (Procedures and Functions)
Stored routines (procedures and functions) are supported in MySQL 5.0. 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.0 installation procedure. If you are upgrading to MySQL 5.0 from an earlier version, be sure to update your grant tables to make sure that the proc table exists. See Section 4.4.9, “ mysql_upgrade — Check Tables for MySQL Upgrade”.
Stored routines can be particularly useful in certain situations:
When multiple client applications are written in different languages or work on different platforms, but need to perform the same database operations.
When security is paramount. Banks, for example, use stored procedures and functions for all common operations. This provides a consistent and secure environment, and routines can ensure that each operation is properly logged. In such a setup, applications and users would have no access to the database tables directly, but can only execute specific stored routines.
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.
The MySQL implementation of stored routines is still in progress. All syntax described here is supported and any limitations and extensions are documented where appropriate.
Additional Resources
You may find the Stored Procedures User Forum of use when working with stored procedures and functions.
For answers to some commonly asked questions regarding stored routines in MySQL, see Section A.4, “MySQL 5.0 FAQ: Stored Procedures and Functions”.
There are some restrictions on the use of stored routines. See Section D.1, “Restrictions on Stored Routines and Triggers”.
Binary logging for stored routines takes place as described in Section 18.6, “Binary Logging of Stored Programs”.
18.2.1. Stored Routine Syntax
A stored routine is either a procedure or a function. Stored routines are created with the CREATE PROCEDURE and CREATE FUNCTION statements (see Section 12.1.9, “ CREATE PROCEDURE and CREATE FUNCTION Syntax”). A procedure is invoked using a CALL statement (see Section 12.2.1, “ CALL Syntax”), and can only pass back values using output variables. A function can be called from inside a statement just like any other function (that is, by invoking the function’s name), and can return a scalar value. The body of a stored routine can use compound statements (see Section 12.7, “MySQL Compound-Statement Syntax”).
As of MySQL 5.0.1, a stored procedure or function is associated with a particular database. This has several implications:
When the routine is invoked, an implicit USE db_name is performed (and undone when the routine terminates). USE statements within stored routines are not permitted.
You can qualify routine names with the database name. This can be used to refer to a routine that is not in the current database. For example, to invoke a stored procedure p or function f that is associated with the test database, you can say CALL test.p() or test.f() .
When a database is dropped, all stored routines associated with it are dropped as well.
(In MySQL 5.0.0, stored routines are global and not associated with a database. They inherit the default database from the caller. If a USE db_name is executed within the routine, the original default database is restored upon routine exit.)
Stored functions cannot be recursive.
Recursion in stored procedures is permitted but disabled by default. To enable recursion, set the max_sp_recursion_depth server system variable to a value greater than zero. Stored procedure recursion increases the demand on thread stack space. If you increase the value of max_sp_recursion_depth , it may be necessary to increase thread stack size by increasing the value of thread_stack at server startup. See Section 5.1.3, “Server System Variables”, for more information.
MySQL supports a very useful extension that enables the use of regular SELECT statements (that is, without using cursors or local variables) inside a stored procedure. The result set of such a query is simply sent directly to the client. Multiple SELECT statements generate multiple result sets, so the client must use a MySQL client library that supports multiple result sets. This means the client must use a client library from a version of MySQL at least as recent as 4.1. The client should also specify the CLIENT_MULTI_RESULTS option when it connects. For C programs, this can be done with the mysql_real_connect() C API function. See Section 20.8.3.52, “ mysql_real_connect() ”, and Section 20.8.12, “C API Support for Multiple Statement Execution”.
18.2.2. Stored Routines and MySQL Privileges
Beginning with MySQL 5.0.3, the grant system takes stored routines into account as follows:
The CREATE ROUTINE privilege is needed to create stored routines.
The ALTER ROUTINE privilege is needed to alter or drop stored routines. This privilege is granted automatically to the creator of a routine if necessary, and dropped from the creator when the routine is dropped.
The EXECUTE privilege is required to execute stored routines. However, this privilege is granted automatically to the creator of a routine if necessary (and dropped from the creator when the routine is dropped). Also, the default SQL SECURITY characteristic for a routine is DEFINER , which enables users who have access to the database with which the routine is associated to execute the routine.
If the automatic_sp_privileges system variable is 0, the EXECUTE and ALTER ROUTINE privileges are not automatically granted to and dropped from the routine creator.
The creator of a routine is the account used to execute the CREATE statement for it. This might not be the same as the account named as the DEFINER in the routine definition.
The server manipulates the mysql.proc table in response to statements that create, alter, or drop stored routines. It is not supported that the server will notice manual manipulation of this table.
18.2.3. Stored Routine Metadata
Metadata about stored routines can be obtained as follows:
INFORMATION_SCHEMA does not have a PARAMETERS table until MySQL 5.5, so applications that need to acquire routine parameter information at runtime must use workarounds such as parsing the output of SHOW CREATE statements or the param_list column of the mysql.proc table. param_list contents can be processed from within a stored routine, unlike the output from SHOW .
18.2.4. Stored Procedures, Functions, Triggers, and LAST_INSERT_ID()
Within the body of a stored routine (procedure or function) or a trigger, the value of LAST_INSERT_ID() changes the same way as for statements executed outside the body of these kinds of objects (see Section 11.13, “Information Functions”). The effect of a stored routine or trigger upon the value of LAST_INSERT_ID() that is seen by following statements depends on the kind of routine:
If a stored procedure executes statements that change the value of LAST_INSERT_ID() , the changed value is seen by statements that follow the procedure call.
For stored functions and triggers that change the value, the value is restored when the function or trigger ends, so following statements do not see a changed value. (Before MySQL 5.0.12, the value is not restored and following statements do see a changed value.)
18.3. Using Triggers
Support for triggers is included beginning with MySQL 5.0.2. A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update.
A trigger is defined to activate when an INSERT , DELETE , or UPDATE statement executes for the associated table. A trigger can be set to activate either before or after the triggering statement. For example, you can have a trigger activate before each row that is inserted into a table or after each row that is updated.
MySQL triggers are activated by SQL statements only . They are not activated by changes in tables made by APIs that do not transmit SQL statements to the MySQL Server; in particular, they are not activated by updates made using the NDB API.
To use triggers if you have upgraded to MySQL 5.0 from an older release that did not support triggers, you should upgrade your grant tables so that they contain the trigger-related privileges. See Section 4.4.9, “ mysql_upgrade — Check Tables for MySQL Upgrade”.
The following discussion describes the syntax for creating and dropping triggers, and shows some examples of how to use them.
Additional Resources
You may find the Triggers User Forum of use when working with views.
For answers to some commonly asked questions regarding triggers in MySQL, see Section A.5, “MySQL 5.0 FAQ: Triggers”.
There are some restrictions on the use of triggers; see Section D.1, “Restrictions on Stored Routines and Triggers”.
Binary logging for triggers takes place as described in Section 18.6, “Binary Logging of Stored Programs”.
18.3.1. Trigger Syntax
To create a trigger or drop a trigger, use the CREATE TRIGGER or DROP TRIGGER statement. The syntax for these statements is described in Section 12.1.11, “ CREATE TRIGGER Syntax”, and Section 12.1.18, “ DROP TRIGGER Syntax”.
Here is a simple example that associates a trigger with a table for INSERT statements. The trigger acts as an accumulator, summing the values inserted into one of the columns of the table.
The CREATE TRIGGER statement creates a trigger named ins_sum that is associated with the account table. It also includes clauses that specify the trigger activation time, the triggering event, and what to do with the trigger activates:
The keyword BEFORE indicates the trigger action time. In this case, the trigger should activate before each row inserted into the table. The other permissible keyword here is AFTER .
The keyword INSERT indicates the event that activates the trigger. In the example, INSERT statements cause trigger activation. You can also create triggers for DELETE and UPDATE statements.
The statement following FOR EACH ROW defines the statement to execute each time the trigger activates, which occurs once for each row affected by the triggering statement In the example, the triggered statement is a simple SET that accumulates the values inserted into the amount column. The statement refers to the column as NEW.amount which means “ the value of the amount column to be inserted into the new row. ”
To use the trigger, set the accumulator variable to zero, execute an INSERT statement, and then see what value the variable has afterward:
In this case, the value of @sum after the INSERT statement has executed is 14.98 + 1937.50 — 100 , or 1852.48 .
To destroy the trigger, use a DROP TRIGGER statement. You must specify the schema name if the trigger is not in the default schema:
Triggers for a table are also dropped if you drop the table.
Trigger names exist in the schema namespace, meaning that all triggers must have unique names within a schema. Triggers in different schemas can have the same name.
In addition to the requirement that trigger names be unique for a schema, there are other limitations on the types of triggers you can create. In particular, you cannot have two triggers for a table that have the same activation time and activation event. For example, you cannot define two BEFORE INSERT triggers or two AFTER UPDATE triggers for a table. This should rarely be a significant limitation, because it is possible to define a trigger that executes multiple statements by using the BEGIN . END compound statement construct after FOR EACH ROW . (An example appears later in this section.)
The OLD and NEW keywords enable you to access columns in the rows affected by a trigger. ( OLD and NEW are not case sensitive.) In an INSERT trigger, only NEW. col_name can be used; there is no old row. In a DELETE trigger, only OLD. col_name can be used; there is no new row. In an UPDATE trigger, you can use OLD. col_name to refer to the columns of a row before it is updated and NEW. col_name to refer to the columns of the row after it is updated.
A column named with OLD is read only. You can refer to it (if you have the SELECT privilege), but not modify it. A column named with NEW can be referred to if you have the SELECT privilege for it. In a BEFORE trigger, you can also change its value with SET NEW. col_name = value if you have the UPDATE privilege for it. This means you can use a trigger to modify the values to be inserted into a new row or that are used to update a row.
In a BEFORE trigger, the NEW value for an AUTO_INCREMENT column is 0, not the automatically generated sequence number that will be generated when the new record actually is inserted.
OLD and NEW are MySQL extensions to triggers.
By using the BEGIN . END construct, you can define a trigger that executes multiple statements. Within the BEGIN block, you also can use other syntax that is permitted within stored routines such as conditionals and loops. However, just as for stored routines, if you use the mysql program to define a trigger that executes multiple statements, it is necessary to redefine the mysql statement delimiter so that you can use the ; statement delimiter within the trigger definition. The following example illustrates these points. It defines an UPDATE trigger that checks the new value to be used for updating each row, and modifies the value to be within the range from 0 to 100. This must be a BEFORE trigger because the value needs to be checked before it is used to update the row:
It can be easier to define a stored procedure separately and then invoke it from the trigger using a simple CALL statement. This is also advantageous if you want to invoke the same routine from within several triggers.
There are some limitations on what can appear in statements that a trigger executes when activated:
The trigger cannot use the CALL statement to invoke stored procedures that return data to the client or that use dynamic SQL. (Stored procedures are permitted to return data to the trigger through OUT or INOUT parameters.)
The trigger cannot use statements that explicitly or implicitly begin or end a transaction such as START TRANSACTION , COMMIT , or ROLLBACK .
Prior to MySQL 5.0.10, triggers cannot contain direct references to tables by name.
MySQL handles errors during trigger execution as follows:
If a BEFORE trigger fails, the operation on the corresponding row is not performed.
A BEFORE trigger is activated by the attempt to insert or modify the row, regardless of whether the attempt subsequently succeeds.
An AFTER trigger is executed only if the BEFORE trigger (if any) and the row operation both execute successfully.
An error during either a BEFORE or AFTER trigger results in failure of the entire statement that caused trigger invocation.
For transactional tables, failure of a statement should cause rollback of all changes performed by the statement. Failure of a trigger causes the statement to fail, so trigger failure also causes rollback. For nontransactional tables, such rollback cannot be done, so although the statement fails, any changes performed prior to the point of the error remain in effect.