Chapter 12. SQL Statement Syntax
Table of Contents
- 12.1. Data Definition Statements
- 12.1.1.
ALTER DATABASESyntax - 12.1.2.
ALTER EVENTSyntax - 12.1.3.
ALTER FUNCTIONSyntax - 12.1.4.
ALTER PROCEDURESyntax - 12.1.5.
ALTER SERVERSyntax - 12.1.6.
ALTER TABLESyntax - 12.1.7.
ALTER VIEWSyntax - 12.1.8.
CREATE DATABASESyntax - 12.1.9.
CREATE EVENTSyntax - 12.1.10.
CREATE FUNCTIONSyntax - 12.1.11.
CREATE INDEXSyntax - 12.1.12.
CREATE PROCEDUREandCREATE FUNCTIONSyntax - 12.1.13.
CREATE SERVERSyntax - 12.1.14.
CREATE TABLESyntax - 12.1.15.
CREATE TRIGGERSyntax - 12.1.16.
CREATE VIEWSyntax - 12.1.17.
DROP DATABASESyntax - 12.1.18.
DROP EVENTSyntax - 12.1.19.
DROP FUNCTIONSyntax - 12.1.20.
DROP INDEXSyntax - 12.1.21.
DROP PROCEDUREandDROP FUNCTIONSyntax - 12.1.22.
DROP SERVERSyntax - 12.1.23.
DROP TABLESyntax - 12.1.24.
DROP TRIGGERSyntax - 12.1.25.
DROP VIEWSyntax - 12.1.26.
RENAME TABLESyntax
- 12.1.1.
- 12.2. Data Manipulation Statements
- 12.3. MySQL Utility Statements
- 12.4. MySQL Transactional and Locking Statements
- 12.5. Database Administration Statements
- 12.6. Replication Statements
- 12.7. SQL Syntax for Prepared Statements
- 12.8. MySQL Compound-Statement Syntax
This chapter describes the syntax for the SQL statements supported by MySQL.
- 12.1.1.
ALTER DATABASESyntax - 12.1.2.
ALTER EVENTSyntax - 12.1.3.
ALTER FUNCTIONSyntax - 12.1.4.
ALTER PROCEDURESyntax - 12.1.5.
ALTER SERVERSyntax - 12.1.6.
ALTER TABLESyntax - 12.1.7.
ALTER VIEWSyntax - 12.1.8.
CREATE DATABASESyntax - 12.1.9.
CREATE EVENTSyntax - 12.1.10.
CREATE FUNCTIONSyntax - 12.1.11.
CREATE INDEXSyntax - 12.1.12.
CREATE PROCEDUREandCREATE FUNCTIONSyntax - 12.1.13.
CREATE SERVERSyntax - 12.1.14.
CREATE TABLESyntax - 12.1.15.
CREATE TRIGGERSyntax - 12.1.16.
CREATE VIEWSyntax - 12.1.17.
DROP DATABASESyntax - 12.1.18.
DROP EVENTSyntax - 12.1.19.
DROP FUNCTIONSyntax - 12.1.20.
DROP INDEXSyntax - 12.1.21.
DROP PROCEDUREandDROP FUNCTIONSyntax - 12.1.22.
DROP SERVERSyntax - 12.1.23.
DROP TABLESyntax - 12.1.24.
DROP TRIGGERSyntax - 12.1.25.
DROP VIEWSyntax - 12.1.26.
RENAME TABLESyntax
ALTER {DATABASE | SCHEMA} [db_name]
alter_specification ...
ALTER {DATABASE | SCHEMA} db_name
UPGRADE DATA DIRECTORY NAME
alter_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
ALTER DATABASE enables you to
change the overall characteristics of a database. These
characteristics are stored in the db.opt file
in the database directory. To use ALTER
DATABASE, you need the
ALTER privilege on the database.
ALTER
SCHEMA is a synonym for ALTER
DATABASE.
The CHARACTER SET clause changes the default
database character set. The COLLATE clause
changes the default database collation. Section 9.1, “Character Set Support”,
discusses character set and collation names.
You can see what character sets and collations are available
using, respectively, the SHOW CHARACTER
SET and SHOW COLLATION
statements. See Section 12.5.6.4, “SHOW CHARACTER SET Syntax”, and
Section 12.5.6.5, “SHOW COLLATION Syntax”, for more information.
The database name can be omitted from the first syntax, in which case the statement applies to the default database.
The syntax that includes the UPGRADE DATA DIRECTORY
NAME clause updates the name of the directory associated
with the database to use the encoding implemented in MySQL 5.1 for
mapping database names to database directory names (see
Section 8.2.3, “Mapping of Identifiers to File Names”). This clause is for use
under these conditions:
It is intended when upgrading MySQL to 5.1 or later from older versions.
It is intended to update a database directory name to the current encoding format if the name contains special characters that need encoding.
The statement is used by mysqlcheck (as invoked by mysql_upgrade).
For example,if a database in MySQL 5.0 has a name of
a-b-c, the name contains instance of the
‘-’ character. In 5.0, the database
directory is also named a-b-c, which is not
necessarily safe for all file systems. In MySQL 5.1 and up, the
same database name is encoded as a@002db@002dc
to produce a file system-neutral directory name.
When a MySQL installation is upgraded to MySQL 5.1 or later from
an older version,the server displays a name such as
a-b-c (which is in the old format) as
#mysql50#a-b-c, and you must refer to the name
using the #mysql50# prefix. Use
UPGRADE DATA DIRECTORY NAME in this case to
explicitly tell the server to re-encode the database directory
name to the current encoding format:
ALTER DATABASE `#mysql50#a-b-c` UPGRADE DATA DIRECTORY NAME;
After executing this statement, you can refer to the database as
a-b-c without the special
#mysql50# prefix.
MySQL Enterprise In a production environment, alteration of a database is not a common occurrence and may indicate a security breach. Advisors provided as part of the MySQL Enterprise Monitor automatically alert you when data definition statements are issued. For more information, see http://www.mysql.com/products/enterprise/advisors.html.
ALTER
[DEFINER = { user | CURRENT_USER }]
EVENT event_name
[ON SCHEDULE schedule]
[ON COMPLETION [NOT] PRESERVE]
[RENAME TO new_event_name]
[ENABLE | DISABLE | DISABLE ON SLAVE]
[COMMENT 'comment']
[DO sql_statement]
The ALTER EVENT statement is used
to change one or more of the characteristics of an existing event
without the need to drop and recreate it. The syntax for each of
the DEFINER, ON SCHEDULE,
ON COMPLETION, COMMENT,
ENABLE / DISABLE, and
DO clauses is exactly the same as
when used with CREATE EVENT. (See
Section 12.1.9, “CREATE EVENT Syntax”.)
Any user can alter an event defined on a database for which that
user has the EVENT privilege. When
a user executes a successful ALTER
EVENT statement, that user becomes the definer for the
affected event.
ALTER EVENT works only with an
existing event:
mysql>ALTER EVENT no_such_event>ON SCHEDULE>EVERY '2:3' DAY_HOUR;ERROR 1517 (HY000): Unknown event 'no_such_event'
In each of the following examples, assume that the event named
myevent is defined as shown here:
CREATE EVENT myevent
ON SCHEDULE
EVERY 6 HOUR
COMMENT 'A sample comment.'
DO
UPDATE myschema.mytable SET mycol = mycol + 1;
The following statement changes the schedule for
myevent from once every six hours starting
immediately to once every twelve hours, starting four hours from
the time the statement is run:
ALTER EVENT myevent
ON SCHEDULE
EVERY 12 HOUR
STARTS CURRENT_TIMESTAMP + INTERVAL 4 HOUR;
It is possible to change multiple characteristics of an event in a
single statement. This example changes the SQL statement executed
by myevent to one that deletes all records from
mytable; it also changes the schedule for the
event such that it executes once, one day after this
ALTER EVENT statement is run.
ALTER TABLE myevent
ON SCHEDULE
AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO
TRUNCATE TABLE myschema.mytable;
It is necessary to include only those options in an
ALTER EVENT statement which
correspond to characteristics that you actually wish to change;
options which are omitted retain their existing values. This
includes any default values for CREATE
EVENT such as ENABLE.
To disable myevent, use this
ALTER EVENT statement:
ALTER EVENT myevent
DISABLE;
A third value may also appear in place of
ENABLED or DISABLED;
DISABLE ON SLAVE is used on a replication slave
to indicate an event which was created on the master and
replicated to the slave, but which is not executed on the slave.
Normally, DISABLE ON SLAVE is set automatically
as required; however, there are some circumstances under which you
may want or need to change it manually. See
Section 16.3.1.7, “Replication of Invoked Features”, for more
information.
The ON SCHEDULE clause may use expressions
involving built-in MySQL functions and user variables to obtain
any of the timestamp or
interval values which it contains. You
may not use stored functions or user-defined functions in such
expressions, nor may you use any table references; however, you
may use SELECT FROM DUAL. This is true for both
ALTER EVENT and
CREATE EVENT statements. References
to stored functions, user-defined functions, and tables in such
cases are specifically disallowed, and fail with an error (see Bug#22830).
An ALTER EVENT statement that
contains another ALTER EVENT
statement in its DO clause appears
to succeed; however, when the server attempts to execute the
resulting scheduled event, the execution fails with an error.
To rename an event, use the ALTER
EVENT statement's RENAME TO clause.
This statement renames the event myevent to
yourevent:
ALTER EVENT myevent
RENAME TO yourevent;
You can also move an event to a different database using
ALTER EVENT ... RENAME TO ... and
notation, as shown here:
db_name.event_name
ALTER EVENT olddb.myevent
RENAME TO newdb.myevent;
To execute the previous statement, the user executing it must have
the EVENT privilege on both the
olddb and newdb databases.
Note
There is no RENAME EVENT statement.
ALTER FUNCTIONfunc_name[characteristic...]characteristic: { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } | SQL SECURITY { DEFINER | INVOKER } | COMMENT 'string'
This statement can be used to change the characteristics of a
stored function. More than one change may be specified in an
ALTER FUNCTION statement. However,
you cannot change the parameters or body of a stored function
using this statement; to make such changes, you must drop and
re-create the function using DROP
FUNCTION and CREATE
FUNCTION.
You must have the ALTER ROUTINE
privilege for the function. (That privilege is granted
automatically to the function creator.) If binary logging is
enabled, the ALTER FUNCTION
statement might also require the
SUPER privilege, as described in
Section 18.6, “Binary Logging of Stored Programs”.
ALTER PROCEDUREproc_name[characteristic...]characteristic: { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } | SQL SECURITY { DEFINER | INVOKER } | COMMENT 'string'
This statement can be used to change the characteristics of a
stored procedure. More than one change may be specified in an
ALTER PROCEDURE statement. However,
you cannot change the parameters or body of a stored procedure
using this statement; to make such changes, you must drop and
re-create the procedure using DROP
PROCEDURE and CREATE
PROCEDURE.
You must have the ALTER ROUTINE
privilege for the procedure. (That privilege is granted
automatically to the procedure creator.)
ALTER SERVERserver_nameOPTIONS (option[,option] ...)
Alters the server information for
,
adjusting the specified options as per the
server_nameCREATE SERVER command. See
Section 12.1.13, “CREATE SERVER Syntax”. The corresponding fields in the
mysql.servers table are updated accordingly.
This statement requires the SUPER
privilege.
For example, to update the USER option:
ALTER SERVER s OPTIONS (USER 'sally');
ALTER SERVER does not cause an
automatic commit.
ALTER [IGNORE] TABLEtbl_namealter_specification[,alter_specification] ...alter_specification:table_options| ADD [COLUMN]col_namecolumn_definition[FIRST | AFTERcol_name] | ADD [COLUMN] (col_namecolumn_definition,...) | ADD {INDEX|KEY} [index_name] [index_type] (index_col_name,...) [index_option] ... | ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) [index_option] ... | ADD [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...) [index_option] ... | ADD FULLTEXT [INDEX|KEY] [index_name] (index_col_name,...) [index_option] ... | ADD SPATIAL [INDEX|KEY] [index_name] (index_col_name,...) [index_option] ... | ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...)reference_definition| ALTER [COLUMN]col_name{SET DEFAULTliteral| DROP DEFAULT} | CHANGE [COLUMN]old_col_namenew_col_namecolumn_definition[FIRST|AFTERcol_name] | MODIFY [COLUMN]col_namecolumn_definition[FIRST | AFTERcol_name] | DROP [COLUMN]col_name| DROP PRIMARY KEY | DROP {INDEX|KEY}index_name| DROP FOREIGN KEYfk_symbol| DISABLE KEYS | ENABLE KEYS | RENAME [TO]new_tbl_name| ORDER BYcol_name[,col_name] ... | CONVERT TO CHARACTER SETcharset_name[COLLATEcollation_name] | [DEFAULT] CHARACTER SET [=]charset_name[COLLATE [=]collation_name] | DISCARD TABLESPACE | IMPORT TABLESPACE |partition_options| ADD PARTITION (partition_definition) | DROP PARTITIONpartition_names| COALESCE PARTITIONnumber| REORGANIZE PARTITIONpartition_namesINTO (partition_definitions) | ANALYZE PARTITIONpartition_names| CHECK PARTITIONpartition_names| OPTIMIZE PARTITIONpartition_names| REBUILD PARTITIONpartition_names| REPAIR PARTITIONpartition_names| REMOVE PARTITIONINGindex_col_name:col_name[(length)] [ASC | DESC]index_type: USING {BTREE | HASH | RTREE}index_option: KEY_BLOCK_SIZE [=]value|index_type| WITH PARSERparser_name| COMMENT 'string'table_options:table_option[[,]table_option] ...
ALTER TABLE enables you to change
the structure of an existing table. For example, you can add or
delete columns, create or destroy indexes, change the type of
existing columns, or rename columns or the table itself. You can
also change the comment for the table and type of the table.
The syntax for many of the allowable alterations is similar to
clauses of the CREATE TABLE
statement. See Section 12.1.14, “CREATE TABLE Syntax”, for more
information.
Some operations may result in warnings if attempted on a table for
which the storage engine does not support the operation. These
warnings can be displayed with SHOW
WARNINGS. See Section 12.5.6.40, “SHOW WARNINGS Syntax”.
In most cases, ALTER TABLE works by
making a temporary copy of the original table. The alteration is
performed on the copy, and then the original table is deleted and
the new one is renamed. While ALTER
TABLE is executing, the original table is readable by
other sessions. Updates and writes to the table are stalled until
the new table is ready, and then are automatically redirected to
the new table without any failed updates. The temporary table is
created in the database directory of the new table. This can be
different from the database directory of the original table if
ALTER TABLE is renaming the table
to a different database.
In some cases, no temporary table is necessary:
Alterations that modify only table metadata and not table data can be made immediately by altering the table's
.frmfile and not touching table contents. The following changes are fast alterations that can be made this way:In some cases, an operation such as changing a
VARCHAR(10)column toVARCHAR(15)may be immediate, but this depends on the storage engine for the table. A change such asVARCHAR(10)to a length greater than 255 is not immediate because data values must be modified from using one byte to store the length to using two bytes.If you use
ALTER TABLEwithout any other options, MySQL simply renames any files that correspond to the tabletbl_nameRENAME TOnew_tbl_nametbl_name. (You can also use theRENAME TABLEstatement to rename tables. See Section 12.1.26, “RENAME TABLESyntax”.) Any privileges granted specifically for the renamed table are not migrated to the new name. They must be changed manually.ALTER TABLE ... ADD PARTITIONcreates no temporary table.ADDorDROPoperations forRANGEorLISTpartitions are immediate operations or nearly so.ADDorCOALESCEoperations forHASHorKEYpartitions copy data between changed partitions; unlessLINEAR HASHorLINEAR KEYwas used, this is much the same as creating a new table (although the operation is done partition by partition).REORGANIZEoperations copy only changed partitions and do not touch unchanged ones.
If other cases, MySQL creates a temporary table, even if the data
wouldn't strictly need to be copied. For MyISAM
tables, you can speed up the index re-creation operation (which is
the slowest part of the alteration process) by setting the
myisam_sort_buffer_size system
variable to a high value.
For information on troubleshooting ALTER
TABLE, see Section B.1.7.1, “Problems with ALTER TABLE”.
To use
ALTER TABLE, you needALTER,INSERT, andCREATEprivileges for the table.ADD INDEXandDROP INDEXoperations are performed online when the indexes are on variable-width columns only.Online operations are noncopying; that is, they do not require that indexes be re-created.
The server determines automatically whether an
ADD INDEXorDROP INDEXoperation can be (and is) performed online or offline; if the column is of a variable-width data type, then the operation is performed online. It is not possible to override the server behavior in this regard.Note
The
CREATE INDEXandDROP INDEXstatements also support online operations. See Section 12.1.11, “CREATE INDEXSyntax”, and Section 12.1.20, “DROP INDEXSyntax”, for more information.IGNOREis a MySQL extension to standard SQL. It controls howALTER TABLEworks if there are duplicates on unique keys in the new table or if warnings occur when strict mode is enabled. IfIGNOREis not specified, the copy is aborted and rolled back if duplicate-key errors occur. IfIGNOREis specified, only the first row is used of rows with duplicates on a unique key, The other conflicting rows are deleted. Incorrect values are truncated to the closest matching acceptable value.table_optionsignifies a table option of the kind that can be used in theCREATE TABLEstatement, such asENGINE,AUTO_INCREMENT, orAVG_ROW_LENGTH. (Section 12.1.14, “CREATE TABLESyntax”, lists all table options.) However,ALTER TABLEignores theDATA DIRECTORYandINDEX DIRECTORYtable options.For example, to convert a table to be an
InnoDBtable, use this statement:ALTER TABLE t1 ENGINE = InnoDB;
The outcome of attempting to change a table's storage engine is affected by whether the desired storage engine is available and the setting of the
NO_ENGINE_SUBSTITUTIONSQL mode, as described in Section 5.1.8, “Server SQL Modes”.To prevent inadvertent loss of data,
ALTER TABLEcannot be used to change the storage engine of a table toMERGEorBLACKHOLE.To change the value of the
AUTO_INCREMENTcounter to be used for new rows, do this:ALTER TABLE t2 AUTO_INCREMENT =
value;You cannot reset the counter to a value less than or equal to any that have already been used. For
MyISAM, if the value is less than or equal to the maximum value currently in theAUTO_INCREMENTcolumn, the value is reset to the current maximum plus one. ForInnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.You can issue multiple
ADD,ALTER,DROP, andCHANGEclauses in a singleALTER TABLEstatement, separated by commas. This is a MySQL extension to standard SQL, which allows only one of each clause perALTER TABLEstatement. For example, to drop multiple columns in a single statement, do this:ALTER TABLE t2 DROP COLUMN c, DROP COLUMN d;
CHANGE,col_nameDROP, andcol_nameDROP INDEXare MySQL extensions to standard SQL.MODIFYis an Oracle extension toALTER TABLE.The word
COLUMNis optional and can be omitted.column_definitionclauses use the same syntax forADDandCHANGEas forCREATE TABLE. See Section 12.1.14, “CREATE TABLESyntax”.You can rename a column using a
CHANGEclause. To do so, specify the old and new column names and the definition that the column currently has. For example, to rename anold_col_namenew_col_namecolumn_definitionINTEGERcolumn fromatob, you can do this:ALTER TABLE t1 CHANGE a b INTEGER;
If you want to change a column's type but not the name,
CHANGEsyntax still requires an old and new column name, even if they are the same. For example:ALTER TABLE t1 CHANGE b b BIGINT NOT NULL;
You can also use
MODIFYto change a column's type without renaming it:ALTER TABLE t1 MODIFY b BIGINT NOT NULL;
When you use
CHANGEorMODIFY,column_definitionmust include the data type and all attributes that should apply to the new column, other than index attributes such asPRIMARY KEYorUNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward. Suppose a columncol1is defined asINT UNSIGNED DEFAULT 1 COMMENT 'my column'and you modify the column as follows:ALTER TABLE t1 MODIFY col1 BIGINT;
The resulting column will be defined as
BIGINT, but will not include the attributesUNSIGNED DEFAULT 1 COMMENT 'my column'. To retain them, the statement should be:ALTER TABLE t1 MODIFY col1 BIGINT UNSIGNED DEFAULT 1 COMMENT 'my column';
When you change a data type using
CHANGEorMODIFY, MySQL tries to convert existing column values to the new type as well as possible.Warning
This conversion may result in alteration of data. For example, if you shorten a string column, values may be truncated. To prevent the operation from succeeding if conversions to the new data type would result in loss of data, enable strict SQL mode before using
ALTER TABLE(see Section 5.1.8, “Server SQL Modes”).To add a column at a specific position within a table row, use
FIRSTorAFTER. The default is to add the column last. You can also usecol_nameFIRSTandAFTERinCHANGEorMODIFYoperations to reorder columns within a table.ALTER ... SET DEFAULTorALTER ... DROP DEFAULTspecify a new default value for a column or remove the old default value, respectively. If the old default is removed and the column can beNULL, the new default isNULL. If the column cannot beNULL, MySQL assigns a default value as described in Section 10.1.4, “Data Type Default Values”.DROP INDEXremoves an index. This is a MySQL extension to standard SQL. See Section 12.1.20, “DROP INDEXSyntax”. If you are unsure of the index name, useSHOW INDEX FROM.tbl_nameIf columns are dropped from a table, the columns are also removed from any index of which they are a part. If all columns that make up an index are dropped, the index is dropped as well. If you use
CHANGEorMODIFYto shorten a column for which an index exists on the column, and the resulting column length is less than the index length, MySQL shortens the index automatically.If a table contains only one column, the column cannot be dropped. If what you intend is to remove the table, use
DROP TABLEinstead.DROP PRIMARY KEYdrops the primary key. If there is no primary key, an error occurs.If you add a
UNIQUE INDEXorPRIMARY KEYto a table, it is stored before any nonunique index so that MySQL can detect duplicate keys as early as possible.Some storage engines allow you to specify an index type when creating an index. The syntax for the
index_typespecifier isUSING. For details abouttype_nameUSING, see Section 12.1.11, “CREATE INDEXSyntax”. The index type should be specified after the column list.index_optionvalues specify additional options for an index.USINGis one such option. For details about allowableindex_optionvalues, see Section 12.1.11, “CREATE INDEXSyntax”.After an
ALTER TABLEstatement, it may be necessary to runANALYZE TABLEto update index cardinality information. See Section 12.5.6.23, “SHOW INDEXSyntax”.ORDER BYenables you to create the new table with the rows in a specific order. Note that the table does not remain in this order after inserts and deletes. This option is useful primarily when you know that you are mostly to query the rows in a certain order most of the time. By using this option after major changes to the table, you might be able to get higher performance. In some cases, it might make sorting easier for MySQL if the table is in order by the column that you want to order it by later.ORDER BYsyntax allows for one or more column names to be specified for sorting, each of which optionally can be followed byASCorDESCto indicate ascending or descending sort order, respectively. The default is ascending order. Only column names are allowed as sort criteria; arbitrary expressions are not allowed.ORDER BYdoes not make sense forInnoDBtables that contain a user-defined clustered index (PRIMARY KEYorNOT NULL UNIQUEindex).InnoDBalways orders table rows according to such an index if one is present.Note
When used on a partitioned table,
ALTER TABLE ... ORDER BYorders rows within each partition only.If you use
ALTER TABLEon aMyISAMtable, all nonunique indexes are created in a separate batch (as forREPAIR TABLE). This should makeALTER TABLEmuch faster when you have many indexes.This feature can be activated explicitly for a
MyISAMtable.ALTER TABLE ... DISABLE KEYStells MySQL to stop updating nonunique indexes.ALTER TABLE ... ENABLE KEYSthen should be used to re-create missing indexes. MySQL does this with a special algorithm that is much faster than inserting keys one by one, so disabling keys before performing bulk insert operations should give a considerable speedup. UsingALTER TABLE ... DISABLE KEYSrequires theINDEXprivilege in addition to the privileges mentioned earlier.While the nonunique indexes are disabled, they are ignored for statements such as
SELECTandEXPLAINthat otherwise would use them.If
ALTER TABLEfor anInnoDBtable results in changes to column values (for example, because a column is truncated),InnoDB'sFOREIGN KEYconstraint checks do not notice possible violations caused by changing the values.The
FOREIGN KEYandREFERENCESclauses are supported by theInnoDBstorage engine, which implementsADD [CONSTRAINT [. See Section 13.7.4.4, “symbol]] FOREIGN KEY (...) REFERENCES ... (...)FOREIGN KEYConstraints”. For other storage engines, the clauses are parsed but ignored. TheCHECKclause is parsed but ignored by all storage engines. See Section 12.1.14, “CREATE TABLESyntax”. The reason for accepting but ignoring syntax clauses is for compatibility, to make it easier to port code from other SQL servers, and to run applications that create tables with references. See Section 1.7.5, “MySQL Differences from Standard SQL”.Important
The inline
REFERENCESspecifications where the references are defined as part of the column specification are silently ignored byInnoDB. InnoDB only acceptsREFERENCESclauses defined as part of a separateFOREIGN KEYspecification.Note
Partitioned tables do not support foreign keys. See Section 17.5, “Restrictions and Limitations on Partitioning”, for more information.
InnoDBsupports the use ofALTER TABLEto drop foreign keys:ALTER TABLE
tbl_nameDROP FOREIGN KEYfk_symbol;For more information, see Section 13.7.4.4, “
FOREIGN KEYConstraints”.You cannot add a foreign key and drop a foreign key in separate clauses of a single
ALTER TABLEstatement. You must use separate statements.For an
InnoDBtable that is created with its own tablespace in an.ibdfile, that file can be discarded and imported. To discard the.ibdfile, use this statement:ALTER TABLE
tbl_nameDISCARD TABLESPACE;This deletes the current
.ibdfile, so be sure that you have a backup first. Attempting to access the table while the tablespace file is discarded results in an error.To import the backup
.ibdfile back into the table, copy it into the database directory, and then issue this statement:ALTER TABLE
tbl_nameIMPORT TABLESPACE;Pending
INSERT DELAYEDstatements are lost if a table is write locked andALTER TABLEis used to modify the table structure.If you want to change the table default character set and all character columns (
CHAR,VARCHAR,TEXT) to a new character set, use a statement like this:ALTER TABLE
tbl_nameCONVERT TO CHARACTER SETcharset_name;For a column that has a data type of
VARCHARor one of theTEXTtypes,CONVERT TO CHARACTER SETwill change the data type as necessary to ensure that the new column is long enough to store as many characters as the original column. For example, aTEXTcolumn has two length bytes, which store the byte-length of values in the column, up to a maximum of 65,535. For alatin1TEXTcolumn, each character requires a single byte, so the column can store up to 65,535 characters. If the column is converted toutf8, each character might require up to four bytes, for a maximum possible length of 4 × 65,535 = 262,140 bytes. That length will not fit in aTEXTcolumn's length bytes, so MySQL will convert the data type toMEDIUMTEXT, which is the smallest string type for which the length bytes can record a value of 262,140. Similarly, aVARCHARcolumn might be converted toMEDIUMTEXT.To avoid data type changes of the type just described, do not use
CONVERT TO CHARACTER SET. Instead, useMODIFYto change individual columns. For example:ALTER TABLE t MODIFY latin1_text_col TEXT CHARACTER SET utf8; ALTER TABLE t MODIFY latin1_varchar_col VARCHAR(
M) CHARACTER SET utf8;If you specify
CONVERT TO CHARACTER SET binary, theCHAR,VARCHAR, andTEXTcolumns are converted to their corresponding binary string types (BINARY,VARBINARY,BLOB). This means that the columns no longer will have a character set and a subsequentCONVERT TOoperation will not apply to them.If
charset_nameisDEFAULT, the database character set is used.Warning
The
CONVERT TOoperation converts column values between the character sets. This is not what you want if you have a column in one character set (likelatin1) but the stored values actually use some other, incompatible character set (likeutf8). In this case, you have to do the following for each such column:ALTER TABLE t1 CHANGE c1 c1 BLOB; ALTER TABLE t1 CHANGE c1 c1 TEXT CHARACTER SET utf8;
The reason this works is that there is no conversion when you convert to or from
BLOBcolumns.To change only the default character set for a table, use this statement:
ALTER TABLE
tbl_nameDEFAULT CHARACTER SETcharset_name;The word
DEFAULTis optional. The default character set is the character set that is used if you do not specify the character set for columns that you add to a table later (for example, withALTER TABLE ... ADD column).Partitioning-related clauses for
ALTER TABLEcan be used with partitioned tables for repartitioning, for adding, dropping, merging, and splitting partitions, and for performing partitioning maintenance.Simply using a
partition_optionsclause withALTER TABLEon a partitioned table repartitions the table according to the partitioning scheme defined by thepartition_options. This clause always begins withPARTITION BY, and follows the same syntax and other rules as apply to thepartition_optionsclause forCREATE TABLE(see Section 12.1.14, “CREATE TABLESyntax”, for more detailed information), and can also be used to partition an existing table that is not already partitioned. For example, consider a (nonpartitioned) table defined as shown here:CREATE TABLE t1 ( id INT, year_col INT );This table can be partitioned by
HASH, using theidcolumn as the partitioning key, into 8 partitions by means of this statement:ALTER TABLE t1 PARTITION BY HASH(id) PARTITIONS 8;The table that results from using an
ALTER TABLE ... PARTITION BYstatement must follow the same rules as one created usingCREATE TABLE ... PARTITION BY. This includes the rules governing the relationship between any unique keys (including any primary key) that the table might have, and the column or columns used in the partitioning expression, as discussed in Section 17.5.1, “Partitioning Keys, Primary Keys, and Unique Keys”. TheCREATE TABLE ... PARTITION BYrules for specifying the number of partitions also apply toALTER TABLE ... PARTITION BY.The
partition_definitionclause forALTER TABLE ADD PARTITIONsupports the same options as the clause of the same name for theCREATE TABLEstatement. (See Section 12.1.14, “CREATE TABLESyntax”, for the syntax and description.) Suppose that you have the partitioned table created as shown here:CREATE TABLE t1 ( id INT, year_col INT ) PARTITION BY RANGE (year_col) ( PARTITION p0 VALUES LESS THAN (1991), PARTITION p1 VALUES LESS THAN (1995), PARTITION p2 VALUES LESS THAN (1999) );You can add a new partition
p3to this table for storing values less than2002as follows:ALTER TABLE t1 ADD PARTITION (PARTITION p3 VALUES LESS THAN (2002));
DROP PARTITIONcan be used to drop one or moreRANGEorLISTpartitions. This statement cannot be used withHASHorKEYpartitions; instead, useCOALESCE PARTITION(see below). Any data that was stored in the dropped partitions named in thepartition_nameslist is discarded. For example, given the tablet1defined previously, you can drop the partitions namedp0andp1as shown here:ALTER TABLE t1 DROP PARTITION p0, p1;
ADD PARTITIONandDROP PARTITIONdo not currently supportIF [NOT] EXISTS. It is also not possible to rename a partition or a partitioned table. Instead, if you wish to rename a partition, you must drop and re-create the partition; if you wish to rename a partitioned table, you must instead drop all partitions, rename the table, and then add back the partitions that were dropped.COALESCE PARTITIONcan be used with a table that is partitioned byHASHorKEYto reduce the number of partitions bynumber. Suppose that you have created tablet2using the following definition:CREATE TABLE t2 ( name VARCHAR (30), started DATE ) PARTITION BY HASH( YEAR(started) ) PARTITIONS 6;You can reduce the number of partitions used by
t2from 6 to 4 using the following statement:ALTER TABLE t2 COALESCE PARTITION 2;
The data contained in the last
numberpartitions will be merged into the remaining partitions. In this case, partitions 4 and 5 will be merged into the first 4 partitions (the partitions numbered 0, 1, 2, and 3).To change some but not all the partitions used by a partitioned table, you can use
REORGANIZE PARTITION. This statement can be used in several ways:To merge a set of partitions into a single partition. This can be done by naming several partitions in the
partition_nameslist and supplying a single definition forpartition_definition.To split an existing partition into several partitions. You can accomplish this by naming a single partition for
partition_namesand providing multiplepartition_definitions.To change the ranges for a subset of partitions defined using
VALUES LESS THANor the value lists for a subset of partitions defined usingVALUES IN.
Note
For partitions that have not been explicitly named, MySQL automatically provides the default names
p0,p1,p2, and so on. The same is true with regard to subpartitions.For more detailed information about and examples of
ALTER TABLE ... REORGANIZE PARTITIONstatements, see Section 17.3, “Partition Management”.Important
Only a single
PARTITION BY,ADD PARTITION,DROP PARTITION,REORGANIZE PARTITION, orCOALESCE PARTITIONclause can be used in a givenALTER TABLEstatement.Several additional options available for providing partition maintenance and repair functionality analogous to that implemented for nonpartitioned tables by statements such as
CHECK TABLEandREPAIR TABLE(which are also supported for partitioned tables, beginning with MySQL 6.0.6 — see note at the end of this item). These includeANALYZE PARTITION,CHECK PARTITION,OPTIMIZE PARTITION,REBUILD PARTITION, andREPAIR PARTITION. Each of these options takes apartition_namesclause consisting of one or more names of partitions, separated by commas. The partitions must already exist in the table to be altered. For more information and examples, see Section 17.3.3, “Maintenance of Partitions”.The
ANALYZE PARTITION,CHECK PARTITION,OPTIMIZE PARTITION, andREPAIR PARTITIONoptions were disabled in MySQL 6.0.5, and re-enabled in MySQL 6.0.6. (Bug#20129) They are not supported for tables which are not partitioned; beginning with MySQL 6.0.8, they are disallowed for such tables.Note
Beginning with MySQL 6.0.6, you can use the statements
ANALYZE TABLE,CHECK TABLE,OPTIMIZE TABLE, andREPAIR TABLEon partitioned tables. See Section 12.5.2, “Table Maintenance Statements”, for more information.REMOVE PARTITIONINGenables you to remove a table's partitioning without otherwise affecting the table or its data. This option can be combined with otherALTER TABLEoptions such as those used to add, drop, or rename drop columns or indexes.Using the
ENGINEoption withALTER TABLEchanges the storage engine used by the table without affecting the partitioning.
With the mysql_info() C API
function, you can find out how many rows were copied, and (when
IGNORE is used) how many rows were deleted due
to duplication of unique key values. See
Section 20.10.3.35, “mysql_info()”.
Here are some examples that show uses of
ALTER TABLE. Begin with a table
t1 that is created as shown here:
CREATE TABLE t1 (a INTEGER,b CHAR(10));
To rename the table from t1 to
t2:
ALTER TABLE t1 RENAME t2;
To change column a from
INTEGER to TINYINT NOT
NULL (leaving the name the same), and to change column
b from CHAR(10) to
CHAR(20) as well as renaming it from
b to c:
ALTER TABLE t2 MODIFY a TINYINT NOT NULL, CHANGE b c CHAR(20);
To add a new TIMESTAMP column named
d:
ALTER TABLE t2 ADD d TIMESTAMP;
To add an index on column d and a
UNIQUE index on column a:
ALTER TABLE t2 ADD INDEX (d), ADD UNIQUE (a);
To remove column c:
ALTER TABLE t2 DROP COLUMN c;
To add a new AUTO_INCREMENT integer column
named c:
ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (c);
Note that we indexed c (as a PRIMARY
KEY) because AUTO_INCREMENT columns
must be indexed, and also that we declare c as
NOT NULL because primary key columns cannot be
NULL.
When you add an AUTO_INCREMENT column, column
values are filled in with sequence numbers automatically. For
MyISAM tables, you can set the first sequence
number by executing SET
INSERT_ID= before
valueALTER TABLE or by using the
AUTO_INCREMENT=
table option. See Section 5.1.5, “Session System Variables”.
value
With MyISAM tables, if you do not change the
AUTO_INCREMENT column, the sequence number is
not affected. If you drop an AUTO_INCREMENT
column and then add another AUTO_INCREMENT
column, the numbers are resequenced beginning with 1.
When replication is used, adding an
AUTO_INCREMENT column to a table might not
produce the same ordering of the rows on the slave and the master.
This occurs because the order in which the rows are numbered
depends on the specific storage engine used for the table and the
order in which the rows were inserted. If it is important to have
the same order on the master and slave, the rows must be ordered
before assigning an AUTO_INCREMENT number.
Assuming that you want to add an AUTO_INCREMENT
column to the table t1, the following
statements produce a new table t2 identical to
t1 but with an
AUTO_INCREMENT column:
CREATE TABLE t2 (id INT AUTO_INCREMENT PRIMARY KEY) SELECT * FROM t1 ORDER BY col1, col2;
This assumes that the table t1 has columns
col1 and col2.
This set of statements will also produce a new table
t2 identical to t1, with the
addition of an AUTO_INCREMENT column:
CREATE TABLE t2 LIKE t1; ALTER TABLE T2 ADD id INT AUTO_INCREMENT PRIMARY KEY; INSERT INTO t2 SELECT * FROM t1 ORDER BY col1, col2;
Important
To guarantee the same ordering on both master and slave,
all columns of t1 must
be referenced in the ORDER BY clause.
Regardless of the method used to create and populate the copy
having the AUTO_INCREMENT column, the final
step is to drop the original table and then rename the copy:
DROP t1; ALTER TABLE t2 RENAME t1;
ALTER
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
This statement changes the definition of a view, which must exist.
The syntax is similar to that for CREATE
VIEW and the effect is the same as for CREATE
OR REPLACE VIEW. See Section 12.1.16, “CREATE VIEW Syntax”. This
statement requires the CREATE VIEW
and DROP privileges for the view,
and some privilege for each column referred to in the
SELECT statement. As of MySQL
6.0.4, ALTER VIEW is allowed only
to the definer or users with the
SUPER privilege.
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[create_specification] ...
create_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
CREATE DATABASE creates a database
with the given name. To use this statement, you need the
CREATE privilege for the database.
CREATE
SCHEMA is a synonym for CREATE
DATABASE.
An error occurs if the database exists and you did not specify
IF NOT EXISTS.
create_specification options specify
database characteristics. Database characteristics are stored in
the db.opt file in the database directory.
The CHARACTER SET clause specifies the default
database character set. The COLLATE clause
specifies the default database collation.
Section 9.1, “Character Set Support”, discusses character set and collation
names.
A database in MySQL is implemented as a directory containing files
that correspond to tables in the database. Because there are no
tables in a database when it is initially created, the
CREATE DATABASE statement creates
only a directory under the MySQL data directory and the
db.opt file. Rules for allowable database
names are given in Section 8.2, “Schema Object Names”. If a database
name contains special characters, the name for the database
directory contains encoded versions of those characters as
described in Section 8.2.3, “Mapping of Identifiers to File Names”.
If you manually create a directory under the data directory (for
example, with mkdir), the server considers it a
database directory and it shows up in the output of
SHOW DATABASES.
You can also use the mysqladmin program to create databases. See Section 4.5.2, “mysqladmin — Client for Administering a MySQL Server”.
CREATE
[DEFINER = { user | CURRENT_USER }]
EVENT
[IF NOT EXISTS]
event_name
ON SCHEDULE schedule
[ON COMPLETION [NOT] PRESERVE]
[ENABLE | DISABLE | DISABLE ON SLAVE]
[COMMENT 'comment']
DO sql_statement;
schedule:
AT timestamp [+ INTERVAL interval] ...
| EVERY interval
[STARTS timestamp [+ INTERVAL interval] ...]
[ENDS timestamp [+ INTERVAL interval] ...]
interval:
quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |
DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}
This statement creates and schedules a new event. It requires the
EVENT privilege for the schema in
which the event is to be created.
The minimum requirements for a valid CREATE
EVENT statement are as follows:
The keywords
CREATE EVENTplus an event name, which uniquely identifies the event in the current schema.An
ON SCHEDULEclause, which determines when and how often the event executes.A
DOclause, which contains the SQL statement to be executed by an event.
This is an example of a minimal CREATE
EVENT statement:
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
UPDATE myschema.mytable SET mycol = mycol + 1;
The previous statement creates an event named
myevent. This event executes once — one
hour following its creation — by running an SQL statement
that increments the value of the
myschema.mytable table's
mycol column by 1.
The event_name must be a valid MySQL
identifier with a maximum length of 64 characters. It may be
delimited using back ticks, and may be qualified with the name of
a database schema. An event is associated with both a MySQL user
(the definer) and a schema, and its name must be unique among
names of events within that schema. In general, the rules
governing event names are the same as those for names of stored
routines. See Section 8.2, “Schema Object Names”.
If no schema is indicated as part of
event_name, the default (current)
schema is assumed.
Note
MySQL uses case-insensitive comparisons when checking for the
uniqueness of event names. This means that, for example, you
cannot have two events named myevent and
MyEvent in the same database schema.
The DEFINER clause specifies the MySQL account
to be used when checking access privileges at event execution
time. If a user value is given, it
should be a MySQL account in
'
format (the same format used in the
user_name'@'host_name'GRANT statement). The
user_name and
host_name values both are required.
CURRENT_USER also can be given as
CURRENT_USER(). The default
DEFINER value is the user who executes the
CREATE EVENT statement. (This is
the same as DEFINER = CURRENT_USER.)
If you specify the DEFINER clause, these rules
determine the legal DEFINER user values:
If you do not have the
SUPERprivilege, the only legaluservalue is your own account, either specified literally or by usingCURRENT_USER. You cannot set the definer to some other account.If you have the
SUPERprivilege, you can specify any syntactically legal account name. If the account does not actually exist, a warning is generated.Although it is possible to create routines with a nonexistent
DEFINERvalue, an error occurs if the routine executes with definer privileges but the definer does not exist at execution time.
Within an event, the CURRENT_USER()
function returns the account used to check privileges at event
execution time, which is the DEFINER user. For
information about user auditing within events, see
Section 5.5.9, “Auditing MySQL Account Activity”.
IF NOT EXISTS has the same meaning for
CREATE EVENT as for
CREATE TABLE: If an event named
event_name already exists in the same
schema, no action is taken, and no error results. (However, a
warning is generated in such cases.)
The ON SCHEDULE clause determines when, how
often, and for how long the
sql_statement defined for the event
repeats. This clause takes one of two forms:
ATis used for a one-time event. It specifies that the event executes one time only at the date and time given bytimestamptimestamp, which must include both the date and time, or must be an expression that resolves to a datetime value. You may use a value of either theDATETIMEorTIMESTAMPtype for this purpose. If the date is in the past, a warning occurs, as shown here:mysql>
SELECT NOW();+---------------------+ | NOW() | +---------------------+ | 2006-02-10 23:59:01 | +---------------------+ 1 row in set (0.04 sec) mysql>CREATE EVENT e_totals->ON SCHEDULE AT '2006-02-10 23:59:00'->DO INSERT INTO test.totals VALUES (NOW());Query OK, 0 rows affected, 1 warning (0.00 sec) mysql>SHOW WARNINGS\G*************************** 1. row *************************** Level: Note Code: 1588 Message: Event execution time is in the past and ON COMPLETION NOT PRESERVE is set. The event was dropped immediately after creation.CREATE EVENTstatements which are themselves invalid — for whatever reason — fail with an error.You may use
CURRENT_TIMESTAMPto specify the current date and time. In such a case, the event acts as soon as it is created.To create an event which occurs at some point in the future relative to the current date and time — such as that expressed by the phrase “three weeks from now” — you can use the optional clause
+ INTERVAL. Theintervalintervalportion consists of two parts, a quantity and a unit of time, and follows the same syntax rules that govern intervals used in theDATE_ADD()function (see Section 11.6, “Date and Time Functions”. The units keywords are also the same, except that you cannot use any units involving microseconds when defining an event. With some interval types, complex time units may be used. For example, “two minutes and ten seconds” can be expressed as+ INTERVAL '2:10' MINUTE_SECOND.You can also combine intervals. For example,
AT CURRENT_TIMESTAMP + INTERVAL 3 WEEK + INTERVAL 2 DAYis equivalent to “three weeks and two days from now”. Each portion of such a clause must begin with+ INTERVAL.To repeat actions at a regular interval, use an
EVERYclause. TheEVERYkeyword is followed by anintervalas described in the previous dicussion of theATkeyword. (+ INTERVALis not used withEVERY.) For example,EVERY 6 WEEKmeans “every six weeks”.Although
+ INTERVALclauses are not allowed in anEVERYclause, you can use the same complex time units allowed in a+ INTERVAL.An
EVERYclause may also contain an optionalSTARTSclause.STARTSis followed by atimestampvalue which indicates when the action should begin repeating, and may also use+ INTERVALin order to specify an amount of time “from now”. For example,intervalEVERY 3 MONTH STARTS CURRENT_TIMESTAMP + INTERVAL 1 WEEKmeans “every three months, beginning one week from now”. Similarly, you can express “every two weeks, beginning six hours and fifteen minutes from now” asEVERY 2 WEEK STARTS CURRENT_TIMESTAMP + INTERVAL '6:15' HOUR_MINUTE. Not specifyingSTARTSis the same as usingSTARTS CURRENT_TIMESTAMP— that is, the action specified for the event begins repeating immediately upon creation of the event.An
EVERYclause may also contain an optionalENDSclause. TheENDSkeyword is followed by atimestampvalue which tells MySQL when the event should stop repeating. You may also use+ INTERVALwithintervalENDS; for instance,EVERY 12 HOUR STARTS CURRENT_TIMESTAMP + INTERVAL 30 MINUTE ENDS CURRENT_TIMESTAMP + INTERVAL 4 WEEKis equivalent to “every twelve hours, beginning thirty minutes from now, and ending four weeks from now”. Not usingENDSmeans that the event continues executing indefinitely.ENDSsupports the same syntax for complex time units asSTARTSdoes.You may use
STARTS,ENDS, both, or neither in anEVERYclause.Note
In MySQL 6.0,
STARTSorENDSuses the MySQL server's local time zone, as shown in theINFORMATION_SCHEMA.EVENTSandmysql.eventtables, as well as in the output ofSHOW EVENTS.See Section 19.20, “The
INFORMATION_SCHEMA EVENTSTable”, and Section 12.5.6.19, “SHOW EVENTSSyntax” for more information.If a repeating event does not terminate within its scheduling interval, the result may be multiple instances of the event executing simultaneously. If this is undesirable, you should institute a mechanism to prevent simultaneous instances. For example, you could use the
GET_LOCK()function, or row or table locking.
The ON SCHEDULE clause may use expressions
involving built-in MySQL functions and user variables to obtain
any of the timestamp or
interval values which it contains. You
may not use stored functions or user-defined functions in such
expressions, nor may you use any table references; however, you
may use SELECT FROM DUAL. This is true for both
CREATE EVENT and
ALTER EVENT statements. References
to stored functions, user-defined functions, and tables in such
cases are specifically disallowed, and fail with an error (see Bug#22830).
Normally, once an event has expired, it is immediately dropped.
You can override this behavior by specifying ON
COMPLETION PRESERVE. Using ON COMPLETION NOT
PRESERVE merely makes the default nonpersistent behavior
explicit.
You can create an event but keep it from being active using the
DISABLE keyword. Alternatively, you may use
ENABLE to make explicit the default status,
which is active. This is most useful in conjunction with
ALTER EVENT (see
Section 12.1.2, “ALTER EVENT Syntax”).
A third value may also appear in place of
ENABLED or DISABLED;
DISABLE ON SLAVE is set for the status of an
event on a replication slave to indicate that the event was
created on the master and replicated to the slave, but is not
executed on the slave. See
Section 16.3.1.7, “Replication of Invoked Features”.
You may supply a comment for an event using a
COMMENT clause.
comment may be any string of up to 64
characters that you wish to use for describing the event. The
comment text, being a string literal, must be surrounded by
quotation marks.
The DO clause specifies an action
carried by the event, and consists of an SQL statement. Nearly any
valid MySQL statement which can be used in a stored routine can
also be used as the action statement for a scheduled event. (See
Section D.1, “Restrictions on Stored Routines, Triggers, and Events”.) For example, the
following event e_hourly deletes all rows from
the sessions table once per hour, where this
table is part of the site_activity schema:
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM site_activity.sessions;
MySQL stores the sql_mode system
variable setting that is in effect at the time an event is
created, and always executes the event with this setting in force,
regardless of the current server SQL mode.
A CREATE EVENT statement that
contains an ALTER EVENT statement
in its DO clause appears to
succeed; however, when the server attempts to execute the
resulting scheduled event, the execution fails with an error.
Note
Statements such as SELECT or
SHOW that merely return a result
set have no effect when used in an event; the output from these
is not sent to the MySQL Monitor, nor is it stored anywhere.
However, you can use statements such as SELECT ...
INTO and
INSERT INTO ...
SELECT that store a result. (See the next example in
this section for an instance of the latter.)
The schema to which an event belongs is the default schema for
table references in the DO clause.
Any references to tables in other schemas must be qualified with
the proper schema name.
As with stored routines, you can use compound-statement syntax in
the DO clause by using the
BEGIN and END keywords, as
shown here:
delimiter |
CREATE EVENT e_daily
ON SCHEDULE
EVERY 1 DAY
COMMENT 'Saves total number of sessions then clears the table each day'
DO
BEGIN
INSERT INTO site_activity.totals (time, total)
SELECT CURRENT_TIMESTAMP, COUNT(*)
FROM site_activity.sessions;
DELETE FROM site_activity.sessions;
END |
delimiter ;
Note the use of the delimiter command to change
the statement delimiter. See
Section 18.1, “Defining Stored Programs”.
More complex compound statements, such as those used in stored routines, are possible in an event. This example uses local variables, an error handler, and a flow control construct:
delimiter |
CREATE EVENT e
ON SCHEDULE
EVERY 5 SECOND
DO
BEGIN
DECLARE v INTEGER;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END;
SET v = 0;
WHILE v < 5 DO
INSERT INTO t1 VALUES (0);
UPDATE t2 SET s1 = s1 + 1;
SET v = v + 1;
END WHILE;
END |
delimiter ;
There is no way to pass parameters directly to or from events; however, it is possible to invoke a stored routine with parameters:
CREATE EVENT e_call_myproc
ON SCHEDULE
AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO CALL myproc(5, 27);
In addition, if the event's definer has the
SUPER privilege, that event may
read and write global variables. As granting this privilege
entails a potential for abuse, extreme care must be taken in doing
so.
Generally, any statements which are valid in stored routines may be used for action statements executed by events. For more information about statements allowable within stored routines, see Section 18.2.1, “Stored Routine Syntax”. You can create an event as part of a stored routine, but an event cannot be created by another event.
The CREATE FUNCTION statement is
used to create stored functions and user-defined functions (UDFs):
For information about creating stored functions, see Section 12.1.12, “
CREATE PROCEDUREandCREATE FUNCTIONSyntax”.For information about creating user-defined functions, see Section 12.5.4.1, “
CREATE FUNCTIONSyntax”.
CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEXindex_name[index_type] ONtbl_name(index_col_name,...) [index_option] ...index_col_name:col_name[(length)] [ASC | DESC]index_type: USING {BTREE | HASH | RTREE}index_option: KEY_BLOCK_SIZE [=]value|index_type| WITH PARSERparser_name| COMMENT 'string'
CREATE INDEX is mapped to an
ALTER TABLE statement to create
indexes. See Section 12.1.6, “ALTER TABLE Syntax”.
CREATE INDEX cannot be used to
create a PRIMARY KEY; use
ALTER TABLE instead. For more
information about indexes, see Section 7.4.4, “How MySQL Uses Indexes”.
Normally, you create all indexes on a table at the time the table
itself is created with CREATE
TABLE. See Section 12.1.14, “CREATE TABLE Syntax”.
CREATE INDEX enables you to add
indexes to existing tables.
A column list of the form (col1,col2,...)
creates a multiple-column index. Index values are formed by
concatenating the values of the given columns.
Indexes can be created that use only the leading part of column
values, using
syntax to specify an index prefix length:
col_name(length)
Prefixes can be specified for
CHAR,VARCHAR,BINARY, andVARBINARYcolumns.BLOBandTEXTcolumns also can be indexed, but a prefix length must be given.Prefix lengths are given in characters for nonbinary string types and in bytes for binary string types. That is, index entries consist of the first
lengthcharacters of each column value forCHAR,VARCHAR, andTEXTcolumns, and the firstlengthbytes of each column value forBINARY,VARBINARY, andBLOBcolumns.For spatial columns, prefix values cannot be given, as described later in this section.
The statement shown here creates an index using the first 10
characters of the name column:
CREATE INDEX part_of_name ON customer (name(10));
If names in the column usually differ in the first 10 characters,
this index should not be much slower than an index created from
the entire name column. Also, using column
prefixes for indexes can make the index file much smaller, which
could save a lot of disk space and might also speed up
INSERT operations.
Prefix lengths are storage engine-dependent (for example, a prefix
can be up to 1000 bytes long for MyISAM tables,
767 bytes for InnoDB tables). Note that prefix
limits are measured in bytes, whereas the prefix length in
CREATE INDEX statements is
interpreted as number of characters for nonbinary data types
(CHAR,
VARCHAR,
TEXT). Take this into account when
specifying a prefix length for a column that uses a multi-byte
character set. For example, utf8 columns
require up to four index bytes per character.
Indexes on variable-width columns are created online; that is, creating the indexes does not require any copying. This is done automatically by the server whenever it determines that it is possible to do so; you do not have to use any special SQL syntax or server options to cause it to happen.
In standard MySQL 6.0 releases, it is not possible to
override the server when it determines that an index is to be
created online. For more information, see
Section 12.1.6, “ALTER TABLE Syntax”.
A UNIQUE index creates a constraint such that
all values in the index must be distinct. An error occurs if you
try to add a new row with a key value that matches an existing
row. For all engines, a UNIQUE index allows
multiple NULL values for columns that can
contain NULL. If you specify a prefix value for
a column in a UNIQUE index, the column values
must be unique within the prefix.
MySQL Enterprise Lack of proper indexes can greatly reduce performance. Subscribe to the MySQL Enterprise Monitor for notification of inefficient use of indexes. For more information, see http://www.mysql.com/products/enterprise/advisors.html.
FULLTEXT indexes are supported only for
MyISAM tables and can include only
CHAR,
VARCHAR, and
TEXT columns. Indexing always
happens over the entire column; column prefix indexing is not
supported and any prefix length is ignored if specified. See
Section 11.8, “Full-Text Search Functions”, for details of operation.
The MyISAM, InnoDB,
NDB, BDB, and
ARCHIVE storage engines support spatial columns
such as (POINT and GEOMETRY.
(Section 11.13, “Spatial Extensions”, describes the spatial data
types.) However, support for spatial column indexing varies among
engines. Spatial and nonspatial indexes are available according to
the following rules.
Spatial indexes (created using SPATIAL INDEX):
Available only for
MyISAMtables. Specifying aSPATIAL INDEXfor other storage engines results in an error.Indexed columns must be
NOT NULL.In MySQL 6.0, column prefix lengths are prohibited. The full width of each column is indexed.
Nonspatial indexes (created with INDEX,
UNIQUE, or PRIMARY KEY):
Allowed for any storage engine that supports spatial columns except
ARCHIVE.Columns can be
NULLunless the index is a primary key.For each spatial column in a non-
SPATIALindex exceptPOINTcolumns, a column prefix length must be specified. (This is the same requirement as for indexedBLOBcolumns.) The prefix length is given in bytes.The index type for a non-
SPATIALindex depends on the storage engine. Currently, B-tree is used.
In MySQL 6.0:
An index_col_name specification can end
with ASC or DESC. These
keywords are allowed for future extensions for specifying
ascending or descending index value storage. Currently, they are
parsed but ignored; index values are always stored in ascending
order.
Following the index column list, index options can be given. An
index_option value can be any of the
following:
KEY_BLOCK_SIZE [=]valueThis option provides a hint to the storage engine about the size in bytes to use for index key blocks. The engine is allowed to change the value if necessary. A value of 0 indicates that the default value should be used.
index_typeSome storage engines allow you to specify an index type when creating an index. The allowable index type values supported by different storage engines are shown in the following table. Where multiple index types are listed, the first one is the default when no index type specifier is given.
Storage Engine Allowable Index Types MyISAMBTREE,RTREEInnoDBBTREEMEMORY/HEAPHASH,BTREENDBHASH,BTREE(see note in text)The
RTREEindex type is allowable only forSPATIALindexes.If you specify an index type that is not legal for a given storage engine, but there is another index type available that the engine can use without affecting query results, the engine uses the available type.
Examples:
CREATE TABLE lookup (id INT) ENGINE = MEMORY; CREATE INDEX id_index USING BTREE ON lookup (id);
TYPEis recognized as a synonym fortype_nameUSING. However,type_nameUSINGis the preferred form.The
index_typeoption can also be given before theONclause. Use of the option in this position is deprecated; support for it is to be dropped in a future MySQL release. If antbl_nameindex_typeoption is given in both the earlier and later positions, the final option applies.WITH PARSERparser_nameThis option can be used only with
FULLTEXTindexes. It associates a parser plugin with the index if full-text indexing and searching operations need special handling. See Section 21.2, “The MySQL Plugin Interface”, for details on creating plugins.Index definitions can include an optional comment of up to 1024 characters.
CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
proc_parameter:
[ IN | OUT | INOUT ] param_name type
func_parameter:
param_name type
type:
Any valid MySQL data type
characteristic:
LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
routine_body:
Valid SQL procedure statement
These statements create stored routines. By default, a routine is
associated with the default database. To associate the routine
explicitly with a given database, specify the name as
db_name.sp_name when you create it.
The CREATE FUNCTION statement is
also used in MySQL to support UDFs (user-defined functions). See
Section 21.3, “Adding New Functions to MySQL”. A UDF can be regarded as an
external stored function. However, do note that stored functions
share their namespace with UDFs. See
Section 8.2.4, “Function Name Parsing and Resolution”, for the rules describing
how the server interprets references to different kinds of
functions.
To invoke a stored procedure, use the
CALL statement (see
Section 12.2.1, “CALL Syntax”). To invoke a stored function, refer to it
in an expression. The function returns a value during expression
evaluation.
To execute the CREATE PROCEDURE or
CREATE FUNCTION statement, it is
necessary to have the CREATE
ROUTINE privilege. By default, MySQL automatically
grants the ALTER ROUTINE and
EXECUTE privileges to the routine
creator. This behavior can be changed by disabling the
automatic_sp_privileges system
variable. See Section 18.2.2, “Stored Routines and MySQL Privileges”. If
binary logging is enabled, the CREATE
FUNCTION statement might also require the
SUPER privilege, as described in
Section 18.6, “Binary Logging of Stored Programs”.
The DEFINER and SQL SECURITY
clauses specify the security context to be used when checking
access privileges at routine execution time, as described later.
If the routine name is the same as the name of a built-in SQL function, a syntax error occurs unless you use a space between the name and the following parenthesis when defining the routine or invoking it later. For this reason, avoid using the names of existing SQL functions for your own stored routines.
The IGNORE_SPACE SQL mode
applies to built-in functions, not to stored routines. It is
always allowable to have spaces after a stored routine name,
regardless of whether
IGNORE_SPACE is enabled.
The parameter list enclosed within parentheses must always be
present. If there are no parameters, an empty parameter list of
() should be used. Parameter names are not case
sensitive.
Each parameter is an IN parameter by default.
To specify otherwise for a parameter, use the keyword
OUT or INOUT before the
parameter name.
Note
Specifying a parameter as IN,
OUT, or INOUT is valid
only for a PROCEDURE.
(FUNCTION parameters are always regarded as
IN parameters.)
An IN parameter passes a value into a
procedure. The procedure might modify the value, but the
modification is not visible to the caller when the procedure
returns. An OUT parameter passes a value from
the procedure back to the caller. Its initial value is
NULL within the procedure, and its value is
visible to the caller when the procedure returns. An
INOUT parameter is initialized by the caller,
can be modified by the procedure, and any change made by the
procedure is visible to the caller when the procedure returns.
For each OUT or INOUT
parameter, pass a user-defined variable in the
CALL statement that invokes the
procedure so that you can obtain its value when the procedure
returns. If you are calling the procedure from within another
stored procedure or function, you can also pass a routine
parameter or local routine variable as an IN or
INOUT parameter.
The following example shows a simple stored procedure that uses an
OUT parameter:
mysql>delimiter //mysql>CREATE PROCEDURE simpleproc (OUT param1 INT)->BEGIN->SELECT COUNT(*) INTO param1 FROM t;->END//Query OK, 0 rows affected (0.00 sec) mysql>delimiter ;mysql>CALL simpleproc(@a);Query OK, 0 rows affected (0.00 sec) mysql>SELECT @a;+------+ | @a | +------+ | 3 | +------+ 1 row in set (0.00 sec)
The example uses the mysql client
delimiter command to change the statement
delimiter from ; to // while
the procedure is being defined. This allows the
; delimiter used in the procedure body to be
passed through to the server rather than being interpreted by
mysql itself. See
Section 18.1, “Defining Stored Programs”.
The RETURNS clause may be specified only for a
FUNCTION, for which it is mandatory. It
indicates the return type of the function, and the function body
must contain a RETURN
statement. If the
valueRETURN statement returns a value of
a different type, the value is coerced to the proper type. For
example, if a function specifies an
ENUM or
SET value in the
RETURNS clause, but the
RETURN statement returns an
integer, the value returned from the function is the string for
the corresponding ENUM member of
set of SET members.
The following example function 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)
Parameter types and function return types can be declared to use
any valid data type, except that the COLLATE
attribute cannot be used prior to MySQL 6.0.12. As of 6.0.12,
COLLATE can be used if preceded by the
CHARACTER SET attribute.
The routine_body consists of a valid
SQL procedure statement. This can be a simple statement such as
SELECT or
INSERT, or it can be a compound
statement written using BEGIN and
END. Compound statements can contain
declarations, loops, and other control structure statements. The
syntax for these statements is described in
Section 12.8, “MySQL Compound-Statement Syntax”.
MySQL allows routines to contain DDL statements, such as
CREATE and DROP. MySQL also
allows stored procedures (but not stored functions) to contain SQL
transaction statements such as
COMMIT. Stored functions may not
contain 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
allow them.
Statements that return a result set can be used within a stored
procedcure but not within a stored function. This prohibition
includes SELECT statements that do
not have an INTO
clause and other
statements such as var_listSHOW,
EXPLAIN, and
CHECK TABLE. For statements that
can be determined at function definition time to return a result
set, a Not allowed to return a result set from a
function error occurs
(ER_SP_NO_RETSET). For statements
that can be determined only at runtime to return a result set, a
PROCEDURE %s can't return a result set in the given
context error occurs
(ER_SP_BADSELECT).
USE statements within stored
routines are disallowed. When a routine is invoked, an implicit
USE is
performed (and undone when the routine terminates). The causes the
routine to have the given default database while it executes.
References to objects in databases other than the routine default
database should be qualified with the appropriate database name.
db_name
For additional information about statements that are not allowed in stored routines, see Section D.1, “Restrictions on Stored Routines, Triggers, and Events”.
For information about invoking stored procedures from within
programs written in a language that has a MySQL interface, see
Section 12.2.1, “CALL Syntax”.
MySQL stores the sql_mode system
variable setting that is in effect at the time a routine is
created, and always executes the routine with this setting in
force, regardless of the server SQL mode in effect when
the routine is invoked.
The switch from the SQL mode of the invoker to that of the routine occurs after evaluation of arguments and assignment of the resulting values to routine parameters. If you define a routine in strict SQL mode but invoke it in nonstrict mode, assignment of arguments to routine parameters does not take place in strict mode. If you require that expressions passed to a routine be assigned in strict SQL mode, you should invoke the routine with strict mode in effect.
A procedure or function is considered “deterministic”
if it always produces the same result for the same input
parameters, and “not deterministic” otherwise. If
neither DETERMINISTIC nor NOT
DETERMINISTIC is given in the routine definition, the
default is NOT DETERMINISTIC.
A routine that contains the NOW()
function (or its synonyms) or
RAND() is nondeterministic, but it
might still be replication-safe. For
NOW(), the binary log includes the
timestamp and replicates correctly.
RAND() also replicates correctly as
long as it is called only a single time during the execution of a
routine. (You can consider the routine execution timestamp and
random number seed as implicit inputs that are identical on the
master and slave.)
Prior to MySQL 6.0.3, the DETERMINISTIC
characteristic is accepted, but not used by the optimizer.
However, if binary logging is enabled, this characteristic always
affects which routine definitions MySQL accepts. See
Section 18.6, “Binary Logging of Stored Programs”.
Several characteristics provide information about the nature of data use by the routine. In MySQL, these characteristics are advisory only. The server does not use them to constrain what kinds of statements a routine will be allowed to execute.
CONTAINS SQLindicates that the routine does not contain statements that read or write data. This is the default if none of these characteristics is given explicitly. Examples of such statements areSET @x = 1orDO RELEASE_LOCK('abc'), which execute but neither read nor write data.NO SQLindicates that the routine contains no SQL statements.READS SQL DATAindicates that the routine contains statements that read data (for example,SELECT), but not statements that write data.MODIFIES SQL DATAindicates that the routine contains statements that may write data (for example,INSERTorDELETE).
The SQL SECURITY characteristic can be used to
specify whether the routine should be executed using the
permissions of the user who creates the routine or the user who
invokes it. The default value is DEFINER. This
feature is new in SQL:2003. The creator or invoker must have
permission to access the database with which the routine is
associated. It is necessary to have the
EXECUTE privilege to be able to
execute the routine. The user that must have this privilege is
either the definer or invoker, depending on how the SQL
SECURITY characteristic is set.
The COMMENT characteristic is a MySQL
extension, and may be used to describe the stored routine. This
information is displayed by the SHOW CREATE
PROCEDURE and SHOW CREATE
FUNCTION statements.
The optional DEFINER clause specifies the MySQL
account to be used when checking access privileges at routine
execution time for routines that have the SQL SECURITY
DEFINER characteristic.
If a user value is given for the
DEFINER clause, it should be a MySQL account in
'
format (the same format used in the
user_name'@'host_name'GRANT statement). The
user_name and
host_name values both are required. The
definer can also be given as
CURRENT_USER or
CURRENT_USER(). The default
DEFINER value is the user who executes the
CREATE PROCEDURE or
CREATE FUNCTION or statement. (This
is the same as DEFINER = CURRENT_USER.)
If you specify the DEFINER clause, these rules
determine the legal DEFINER user values:
If you do not have the
SUPERprivilege, the only legaluservalue is your own account, either specified literally or by usingCURRENT_USER. You cannot set the definer to some other account.If you have the
SUPERprivilege, you can specify any syntactically legal account name. If the account does not actually exist, a warning is generated.Although it is possible to create routines with a nonexistent
DEFINERvalue, an error occurs if the routine executes with definer privileges but the definer does not exist at execution time.
Within a stored routine that is defined with the SQL
SECURITY DEFINER characteristic,
CURRENT_USER returns the routine's
DEFINER value. For information about user
auditing within stored routines, see
Section 5.5.9, “Auditing MySQL Account Activity”.
Consider the following procedure, which displays a count of the
number of MySQL accounts listed in the
mysql.user table:
CREATE DEFINER = 'admin'@'localhost' PROCEDURE account_count() BEGIN SELECT 'Number of accounts:', COUNT(*) FROM mysql.user; END;
The procedure is assigned a DEFINER account of
'admin'@'localhost' no matter which user
defines it. It executes with the privileges of that account no
matter which user invokes it (because the default security
characteristic is DEFINER). The procedure
succeeds or fails depending on whether
'admin'@'localhost' has the
EXECUTE privilege for it and the
SELECT privilege for the
mysql.user table.
Now suppose that the procedure is defined with the SQL
SECURITY INVOKER characteristic:
CREATE DEFINER = 'admin'@'localhost' PROCEDURE account_count() SQL SECURITY INVOKER BEGIN SELECT 'Number of accounts:', COUNT(*) FROM mysql.user; END;
The procedure still has a DEFINER of
'admin'@'localhost', but in this case, it
executes with the privileges of the invoking user. Thus, the
procedure succeeds or fails depending on whether the invoker has
the required privileges.
The server handles the data type of a routine parameter, local
routine variable created with
DECLARE, or function return value
as follows:
Assignments are checked for data type mismatches and overflow. Conversion and overflow problems result in warnings, or errors in strict SQL mode.
Only scalar values can be assigned. For example, a statement such as
SET x = (SELECT 1, 2)is invalid.For character data types, if there is a
CHARACTER SETattribute in the declaration, the specified character set and its default collation is used. If theCOLLATEattribute is also present, that collation is used rather than the default collation. If there is noCHARACTER SETattribute, the database character set and collation in effect at routine creation time are used. (The database character set and collation are given by the value of thecharacter_set_databaseandcollation_databasesystem variables.)Prior to MySQL 6.0.12, if there is a
CHARACTER SETattribute in the declaration, theCOLLATEattribute is not supported, and the character set's default collation is used. (This includes use ofBINARY, because in this contextBINARYspecifies the binary collation of the character set.) If there is noCHARACTER SETattribute, the database character set and its default collation (rather than the database collation) are used.
CREATE SERVERserver_nameFOREIGN DATA WRAPPERwrapper_nameOPTIONS (option[,option] ...)option: { HOSTcharacter-literal| DATABASEcharacter-literal| USERcharacter-literal| PASSWORDcharacter-literal| SOCKETcharacter-literal| OWNERcharacter-literal| PORTnumeric-literal}
This statement creates the definition of a server for use with the
FEDERATED storage engine. The
CREATE SERVER statement creates a
new row within the servers table within the
mysql database. This statement requires the
SUPER privilege.
The
should be a unique reference to the server. Server definitions are
global within the scope of the server, it is not possible to
qualify the server definition to a specific database.
server_name has a
maximum length of 64 characters (names longer than 64 characters
are silently truncated), and is case insensitive. You may specify
the name as a quoted string.
server_name
The
should be wrapper_namemysql, and may be quoted with single
quotes. Other values for
are not
currently supported.
wrapper_name
For each you
must specify either a character literal or numeric literal.
Character literals are UTF-8, support a maximum length of 64
characters and default to a blank (empty) string. String literals
are silently truncated to 64 characters. Numeric literals must be
a number between 0 and 9999, default value is 0.
option
The CREATE SERVER statement creates
an entry in the mysql.server table that can
later be used with the CREATE TABLE
statement when creating a FEDERATED table. The
options that you specify will be used to populate the columns in
the mysql.server table. The table columns are
Server_name, Host,
Db, Username,
Password, Port and
Socket.
Note
Note that the OWNER option is currently not
applied, and has no effect on the ownership or operation of the
server connection that is created.
For example:
CREATE SERVER s FOREIGN DATA WRAPPER mysql OPTIONS (USER 'Remote', HOST '192.168.1.106', DATABASE 'test');
The data stored in the table can be used when creating a
connection to a FEDERATED table:
CREATE TABLE t (s1 INT) ENGINE=FEDERATED CONNECTION='s';
For more information, see
Section 13.12, “The FEDERATED Storage Engine”.
CREATE SERVER does not cause an
automatic commit.
CREATE [TEMPORARY] TABLE [IF NOT EXISTS]tbl_name(create_definition,...) [table_options] [partition_options]
Or:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS]tbl_name[(create_definition,...)] [table_options] [partition_options]select_statement
Or:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS]tbl_name{ LIKEold_tbl_name| (LIKEold_tbl_name) }
create_definition:col_namecolumn_definition| [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) [index_option] ... | {INDEX|KEY} [index_name] [index_type] (index_col_name,...) [index_option] ... | [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...) [index_option] ... | {FULLTEXT|SPATIAL} [INDEX|KEY] [index_name] (index_col_name,...) [index_option] ... | [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...)reference_definition| [CONSTRAINT [symbol]] CHECK (expr)column_definition:data_type[NOT NULL | NULL] [DEFAULTdefault_value] [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] [COMMENT 'string'] [reference_definition]data_type: BIT[(length)] | TINYINT[(length)] [UNSIGNED] [ZEROFILL] | SMALLINT[(length)] [UNSIGNED] [ZEROFILL] | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] | INT[(length)] [UNSIGNED] [ZEROFILL] | INTEGER[(length)] [UNSIGNED] [ZEROFILL] | BIGINT[(length)] [UNSIGNED] [ZEROFILL] | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] | DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL] | NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL] | DATE | TIME | TIMESTAMP | DATETIME | YEAR | CHAR[(length)] [CHARACTER SETcharset_name] [COLLATEcollation_name] | VARCHAR(length) [CHARACTER SETcharset_name] [COLLATEcollation_name] | BINARY[(length)] | VARBINARY(length) | TINYBLOB | BLOB | MEDIUMBLOB | LONGBLOB | TINYTEXT [BINARY] [CHARACTER SETcharset_name] [COLLATEcollation_name] | TEXT [BINARY] [CHARACTER SETcharset_name] [COLLATEcollation_name] | MEDIUMTEXT [BINARY] [CHARACTER SETcharset_name] [COLLATEcollation_name] | LONGTEXT [BINARY] [CHARACTER SETcharset_name] [COLLATEcollation_name] | ENUM(value1,value2,value3,...) [CHARACTER SETcharset_name] [COLLATEcollation_name] | SET(value1,value2,value3,...) [CHARACTER SETcharset_name] [COLLATEcollation_name] |spatial_typeindex_col_name:col_name[(length)] [ASC | DESC]index_type: USING {BTREE | HASH | RTREE}index_option: KEY_BLOCK_SIZE [=]value|index_type| WITH PARSERparser_name| COMMENT 'string'reference_definition: REFERENCEStbl_name(index_col_name,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETEreference_option] [ON UPDATEreference_option]reference_option: RESTRICT | CASCADE | SET NULL | NO ACTIONtable_options:table_option[[,]table_option] ...table_option: ENGINE [=]engine_name| AUTO_INCREMENT [=]value| AVG_ROW_LENGTH [=]value| [DEFAULT] CHARACTER SET [=]charset_name| CHECKSUM [=] {0 | 1} | [DEFAULT] COLLATE [=]collation_name| COMMENT [=] 'string' | CONNECTION [=] 'connect_string' | DATA DIRECTORY [=] 'absolute path to directory' | DELAY_KEY_WRITE [=] {0 | 1} | INDEX DIRECTORY [=] 'absolute path to directory' | INSERT_METHOD [=] { NO | FIRST | LAST } | KEY_BLOCK_SIZE [=]value| MAX_ROWS [=]value| MIN_ROWS [=]value| PACK_KEYS [=] {0 | 1 | DEFAULT} | PASSWORD [=] 'string' | ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT} | TABLESPACEtablespace_name| UNION [=] (tbl_name[,tbl_name]...)partition_options: PARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY(column_list) | RANGE(expr) | LIST(expr) } [PARTITIONSnum] [SUBPARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY(column_list) } [SUBPARTITIONSnum] ] [(partition_definition[,partition_definition] ...)]partition_definition: PARTITIONpartition_name[VALUES {LESS THAN {(expr) |MAXVALUE} | IN (value_list)}] [[STORAGE] ENGINE [=]engine_name] [COMMENT [=]'comment_text'] [DATA DIRECTORY [=] ''] [INDEX DIRECTORY [=] 'data_dir'] [MAX_ROWS [=]index_dirmax_number_of_rows] [MIN_ROWS [=]min_number_of_rows] [TABLESPACE [=]tablespace_name] [NODEGROUP [=]node_group_id] [(subpartition_definition[,subpartition_definition] ...)]subpartition_definition: SUBPARTITIONlogical_name[[STORAGE] ENGINE [=]engine_name] [COMMENT [=]'comment_text'] [DATA DIRECTORY [=] ''] [INDEX DIRECTORY [=] 'data_dir'] [MAX_ROWS [=]index_dirmax_number_of_rows] [MIN_ROWS [=]min_number_of_rows] [TABLESPACE [=]tablespace_name] [NODEGROUP [=]node_group_id]select_statement:[IGNORE | REPLACE] [AS] SELECT ... (Some legal select statement)
CREATE TABLE creates a table with
the given name. You must have the
CREATE privilege for the table.
Rules for allowable table names are given in Section 8.2, “Schema Object Names”. By default, the table is created in the default database. An error occurs if the table exists, if there is no default database, or if the database does not exist.
The table name can be specified as
db_name.tbl_name to create the table in
a specific database. This works regardless of whether there is a
default database, assuming that the database exists. If you use
quoted identifiers, quote the database and table names separately.
For example, write `mydb`.`mytbl`, not
`mydb.mytbl`.
You can use the TEMPORARY keyword when creating
a table. A TEMPORARY table is visible only to
the current connection, and is dropped automatically when the
connection is closed. This means that two different connections
can use the same temporary table name without conflicting with
each other or with an existing non-TEMPORARY
table of the same name. (The existing table is hidden until the
temporary table is dropped.) To create temporary tables, you must
have the CREATE TEMPORARY TABLES
privilege.
Note
CREATE TABLE does not
automatically commit the current active transaction if you use
the TEMPORARY keyword.
The keywords IF NOT EXISTS prevent an error
from occurring if the table exists. However, there is no
verification that the existing table has a structure identical to
that indicated by the CREATE TABLE
statement.
MySQL represents each table by an .frm table
format (definition) file in the database directory. The storage
engine for the table might create other files as well. In the case
of MyISAM tables, the storage engine creates
data and index files. Thus, for each MyISAM
table tbl_name, there are three disk
files.
| File | Purpose |
| Table format (definition) file |
| Data file |
| Index file |
Chapter 13, Storage Engines, describes what files each storage engine creates to represent tables. If a table name contains special characters, the names for the table files contain encoded versions of those characters as described in Section 8.2.3, “Mapping of Identifiers to File Names”.
data_type represents the data type in a
column definition. spatial_type
represents a spatial data type. The data type syntax shown is
representative only. For a full description of the syntax
available for specifying column data types, as well as information
about the properties of each type, see
Chapter 10, Data Types, and
Section 11.13, “Spatial Extensions”.
Some attributes do not apply to all data types.
AUTO_INCREMENT applies only to integer and
floating-point types. DEFAULT does not apply to
the BLOB or
TEXT types.
If neither
NULLnorNOT NULLis specified, the column is treated as thoughNULLhad been specified.An integer or floating-point column can have the additional attribute
AUTO_INCREMENT. When you insert a value ofNULL(recommended) or0into an indexedAUTO_INCREMENTcolumn, the column is set to the next sequence value. Typically this is, wherevalue+1valueis the largest value for the column currently in the table.AUTO_INCREMENTsequences begin with1.To retrieve an
AUTO_INCREMENTvalue after inserting a row, use theLAST_INSERT_ID()SQL function or themysql_insert_id()C API function. See Section 11.11.3, “Information Functions”, and Section 20.10.3.37, “mysql_insert_id()”.If the
NO_AUTO_VALUE_ON_ZEROSQL mode is enabled, you can store0inAUTO_INCREMENTcolumns as0without generating a new sequence value. See Section 5.1.8, “Server SQL Modes”.Note
There can be only one
AUTO_INCREMENTcolumn per table, it must be indexed, and it cannot have aDEFAULTvalue. AnAUTO_INCREMENTcolumn works properly only if it contains only positive values. Inserting a negative number is regarded as inserting a very large positive number. This is done to avoid precision problems when numbers “wrap” over from positive to negative and also to ensure that you do not accidentally get anAUTO_INCREMENTcolumn that contains0.For
MyISAMtables, you can specify anAUTO_INCREMENTsecondary column in a multiple-column key. See Section 3.6.9, “UsingAUTO_INCREMENT”.To make MySQL compatible with some ODBC applications, you can find the
AUTO_INCREMENTvalue for the last inserted row with the following query:SELECT * FROM
tbl_nameWHEREauto_colIS NULLFor information about
InnoDBandAUTO_INCREMENT, see Section 13.7.4.3, “AUTO_INCREMENTHandling inInnoDB”.Character data types (
CHAR,VARCHAR,TEXT) can includeCHARACTER SETandCOLLATEattributes to specify the character set and collation for the column. For details, see Section 9.1, “Character Set Support”.CHARSETis a synonym forCHARACTER SET. Example:CREATE TABLE t (c CHAR(20) CHARACTER SET utf8 COLLATE utf8_bin);
MySQL 6.0 interprets length specifications in character column definitions in characters. (Versions before MySQL 4.1 interpreted them in bytes.) Lengths for
BINARYandVARBINARYare in bytes.The
DEFAULTclause specifies a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such asNOW()orCURRENT_DATE. The exception is that you can specifyCURRENT_TIMESTAMPas the default for aTIMESTAMPcolumn. See Section 10.3.1.1, “TIMESTAMPProperties”.If a column definition includes no explicit
DEFAULTvalue, MySQL determines the default value as described in Section 10.1.4, “Data Type Default Values”.BLOBandTEXTcolumns cannot be assigned a default value.CREATE TABLEfails if a date-valued default is not correct according to theNO_ZERO_IN_DATESQL mode, even if strict SQL mode is not enabled. For example,c1 DATE DEFAULT '2010-00-00'causesCREATE TABLEto fail withInvalid default value for 'c1'.A comment for a column can be specified with the
COMMENToption, up to 1024 characters long. The comment is displayed by theSHOW CREATE TABLEandSHOW FULL COLUMNSstatements.KEYis normally a synonym forINDEX. The key attributePRIMARY KEYcan also be specified as justKEYwhen given in a column definition. This was implemented for compatibility with other database systems.A
UNIQUEindex creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, aUNIQUEindex allows multipleNULLvalues for columns that can containNULL.A
PRIMARY KEYis a unique index where all key columns must be defined asNOT NULL. If they are not explicitly declared asNOT NULL, MySQL declares them so implicitly (and silently). A table can have only onePRIMARY KEY. If you do not have aPRIMARY KEYand an application asks for thePRIMARY KEYin your tables, MySQL returns the firstUNIQUEindex that has noNULLcolumns as thePRIMARY KEY.In
InnoDBtables, having a longPRIMARY KEYwastes a lot of space. (See Section 13.7.10, “InnoDBTable and Index Structures”.)In the created table, a
PRIMARY KEYis placed first, followed by allUNIQUEindexes, and then the nonunique indexes. This helps the MySQL optimizer to prioritize which index to use and also more quickly to detect duplicatedUNIQUEkeys.A
PRIMARY KEYcan be a multiple-column index. However, you cannot create a multiple-column index using thePRIMARY KEYkey attribute in a column specification. Doing so only marks that single column as primary. You must use a separatePRIMARY KEY(clause.index_col_name, ...)If a
PRIMARY KEYorUNIQUEindex consists of only one column that has an integer type, you can also refer to the column as_rowidinSELECTstatements.In MySQL, the name of a
PRIMARY KEYisPRIMARY. For other indexes, if you do not assign a name, the index is assigned the same name as the first indexed column, with an optional suffix (_2,_3,...) to make it unique. You can see index names for a table usingSHOW INDEX FROM. See Section 12.5.6.23, “tbl_nameSHOW INDEXSyntax”.Some storage engines allow you to specify an index type when creating an index. The syntax for the
index_typespecifier isUSING.type_nameExample:
CREATE TABLE lookup (id INT, INDEX USING BTREE (id)) ENGINE = MEMORY;
The
USINGclause should be given after the column list.index_optionvalues specify additional options for an index.USINGis one such option. For details about allowableindex_optionvalues, see Section 12.1.11, “CREATE INDEXSyntax”.For more information about indexes, see Section 7.4.4, “How MySQL Uses Indexes”.
In MySQL 6.0, only the
MyISAM,InnoDB, andMEMORYstorage engines support indexes on columns that can haveNULLvalues. In other cases, you must declare indexed columns asNOT NULLor an error results.For
CHAR,VARCHAR,BINARY, andVARBINARYcolumns, indexes can be created that use only the leading part of column values, usingsyntax to specify an index prefix length.col_name(length)BLOBandTEXTcolumns also can be indexed, but a prefix length must be given. Prefix lengths are given in characters for nonbinary string types and in bytes for binary string types. That is, index entries consist of the firstlengthcharacters of each column value forCHAR,VARCHAR, andTEXTcolumns, and the firstlengthbytes of each column value forBINARY,VARBINARY, andBLOBcolumns. Indexing only a prefix of column values like this can make the index file much smaller. See Section 7.4.2, “Column Indexes”.Only the
MyISAMandInnoDBstorage engines support indexing onBLOBandTEXTcolumns. For example:CREATE TABLE test (blob_col BLOB, INDEX(blob_col(10)));
Prefixes can be up to 1000 bytes long (767 bytes for
InnoDBtables). Note that prefix limits are measured in bytes, whereas the prefix length inCREATE TABLEstatements is interpreted as number of characters for nonbinary data types (CHAR,VARCHAR,TEXT). Take this into account when specifying a prefix length for a column that uses a multi-byte character set.An
index_col_namespecification can end withASCorDESC. These keywords are allowed for future extensions for specifying ascending or descending index value storage. Currently, they are parsed but ignored; index values are always stored in ascending order.When you use
ORDER BYorGROUP BYon aTEXTorBLOBcolumn in aSELECT, the server sorts values using only the initial number of bytes indicated by themax_sort_lengthsystem variable. See Section 10.4.3, “TheBLOBandTEXTTypes”.You can create special
FULLTEXTindexes, which are used for full-text searches. Only theMyISAMstorage engine supportsFULLTEXTindexes. They can be created only fromCHAR,VARCHAR, andTEXTcolumns. Indexing always happens over the entire column; column prefix indexing is not supported and any prefix length is ignored if specified. See Section 11.8, “Full-Text Search Functions”, for details of operation. AWITH PARSERclause can be specified as anindex_optionvalue to associate a parser plugin with the index if full-text indexing and searching operations need special handling. This clause is legal only forFULLTEXTindexes. See Section 21.2, “The MySQL Plugin Interface”, for details on creating plugins.You can create
SPATIALindexes on spatial data types. Spatial types are supported only forMyISAMtables and indexed columns must be declared asNOT NULL. See Section 11.13, “Spatial Extensions”.Index definitions can include an optional comment of up to 1024 characters.
InnoDBtables support checking of foreign key constraints. See Section 13.7, “TheInnoDBStorage Engine”. Note that theFOREIGN KEYsyntax inInnoDBis more restrictive than the syntax presented for theCREATE TABLEstatement at the beginning of this section: The columns of the referenced table must always be explicitly named.InnoDBsupports bothON DELETEandON UPDATEactions on foreign keys. For the precise syntax, see Section 13.7.4.4, “FOREIGN KEYConstraints”.For other storage engines, MySQL Server parses and ignores the
FOREIGN KEYandREFERENCESsyntax inCREATE TABLEstatements. TheCHECKclause is parsed but ignored by all storage engines. See Section 1.7.5.4, “Foreign Keys”.Important
For users familiar with the ANSI/ISO SQL Standard, please note that no storage engine, including
InnoDB, recognizes or enforces theMATCHclause used in referential integrity constraint definitions. Use of an explicitMATCHclause will not have the specified effect, and also causesON DELETEandON UPDATEclauses to be ignored. For these reasons, specifyingMATCHshould be avoided.The
MATCHclause in the SQL standard controls howNULLvalues in a composite (multiple-column) foreign key are handled when comparing to a primary key.InnoDBessentially implements the semantics defined byMATCH SIMPLE, which allow a foreign key to be all or partiallyNULL. In that case, the (child table) row containing such a foreign key is allowed to be inserted, and does not match any row in the referenced (parent) table. It is possible to implement other semantics using triggers.Additionally, MySQL and
InnoDBrequire that the referenced columns be indexed for performance. However, the system does not enforce a requirement that the referenced columns beUNIQUEor be declaredNOT NULL. The handling of foreign key references to nonunique keys or keys that containNULLvalues is not well defined for operations such asUPDATEorDELETE CASCADE. You are advised to use foreign keys that reference onlyUNIQUEandNOT NULLkeys.Furthermore,
InnoDBdoes not recognize or support “inlineREFERENCESspecifications” (as defined in the SQL standard) where the references are defined as part of the column specification.InnoDBacceptsREFERENCESclauses only when specified as part of a separateFOREIGN KEYspecification. For other storage engines, MySQL Server parses and ignores foreign key specifications.Note
Partitioned tables do not support foreign keys. See Section 17.5, “Restrictions and Limitations on Partitioning”, for more information.
There is a hard limit of 4096 columns per table, but the effective maximum may be less for a given table and depends on the factors discussed in Section D.9.2, “The Maximum Number of Columns Per Table”.
The ENGINE table option specifies the storage
engine for the table.
The ENGINE table option takes the storage
engine names shown in the following table.
| Storage Engine | Description |
ARCHIVE | The archiving storage engine. See
Section 13.13, “The ARCHIVE Storage Engine”. |
CSV | Tables that store rows in comma-separated values format. See
Section 13.14, “The CSV Storage Engine”. |
EXAMPLE | An example engine. See Section 13.11, “The EXAMPLE Storage Engine”. |
FEDERATED | Storage engine that accesses remote tables. See
Section 13.12, “The FEDERATED Storage Engine”. |
HEAP | This is a synonym for MEMORY. |
ISAM (OBSOLETE) | Not available in MySQL 6.0. If you are upgrading to MySQL
6.0 from a previous version, you should
convert any existing ISAM tables to
MyISAM before
performing the upgrade. |
InnoDB | Transaction-safe tables with row locking and foreign keys. See
Section 13.7, “The InnoDB Storage Engine”. |
MEMORY | The data for this storage engine is stored only in memory. See
Section 13.10, “The MEMORY (HEAP) Storage Engine”. |
MERGE | A collection of MyISAM tables used as one table. Also
known as MRG_MyISAM. See
Section 13.9, “The MERGE Storage Engine”. |
MyISAM | The binary portable storage engine that is the default storage engine
used by MySQL. See
Section 13.5, “The MyISAM Storage Engine”. |
If a storage engine is specified that is not available, MySQL uses
the default engine instead. Normally, this is
MyISAM. For example, if a table definition
includes the ENGINE=INNODB option but the MySQL
server does not support INNODB tables, the
table is created as a MyISAM table. This makes
it possible to have a replication setup where you have
transactional tables on the master but tables created on the slave
are nontransactional (to get more speed). In MySQL
6.0, a warning occurs if the storage engine
specification is not honored.
Engine substitution can be controlled by the setting of the
NO_ENGINE_SUBSTITUTION SQL mode,
as described in Section 5.1.8, “Server SQL Modes”.
Note
The older TYPE option was synonymous with
ENGINE. TYPE was
deprecated in MySQL 4.0, and removed in MySQL 5.2.
When upgrading to MySQL 5.2 or later, you must convert
existing applications that rely on TYPE to
use ENGINE instead.
The other table options are used to optimize the behavior of the
table. In most cases, you do not have to specify any of them.
These options apply to all storage engines unless otherwise
indicated. Options that do not apply to a given storage engine may
be accepted and remembered as part of the table definition. Such
options then apply if you later use ALTER
TABLE to convert the table to use a different storage
engine.
AUTO_INCREMENTThe initial
AUTO_INCREMENTvalue for the table. In MySQL 6.0, this works forMyISAM,MEMORY,InnoDB,ARCHIVEandFalcontables. To set the first auto-increment value for engines that do not support theAUTO_INCREMENTtable option, insert a “dummy” row with a value one less than the desired value after creating the table, and then delete the dummy row.For engines that support the
AUTO_INCREMENTtable option inCREATE TABLEstatements, you can also useALTER TABLEto reset thetbl_nameAUTO_INCREMENT =NAUTO_INCREMENTvalue. The value cannot be set lower than the maximum value currently in the column.AVG_ROW_LENGTHAn approximation of the average row length for your table. You need to set this only for large tables with variable-size rows.
When you create a
MyISAMtable, MySQL uses the product of theMAX_ROWSandAVG_ROW_LENGTHoptions to decide how big the resulting table is. If you don't specify either option, the maximum size forMyISAMdata and index files is 256TB by default. (If your operating system does not support files that large, table sizes are constrained by the file size limit.) If you want to keep down the pointer sizes to make the index smaller and faster and you don't really need big files, you can decrease the default pointer size by setting themyisam_data_pointer_sizesystem variable. (See Section 5.1.4, “Server System Variables”.) If you want all your tables to be able to grow above the default limit and are willing to have your tables slightly slower and larger than necessary, you can increase the default pointer size by setting this variable. Setting the value to 7 allows table sizes up to 65,536TB.[DEFAULT] CHARACTER SETSpecify a default character set for the table.
CHARSETis a synonym forCHARACTER SET. If the character set name isDEFAULT, the database character set is used.CHECKSUMSet this to 1 if you want MySQL to maintain a live checksum for all rows (that is, a checksum that MySQL updates automatically as the table changes). This makes the table a little slower to update, but also makes it easier to find corrupted tables. The
CHECKSUM TABLEstatement reports the checksum. (MyISAMonly.)[DEFAULT] COLLATESpecify a default collation for the table.
COMMENTA comment for the table, up to 2048 characters long. (Before 5.2.4, the limit is 60 characters.)
CONNECTIONThe connection string for a
FEDERATEDtable.Note
Older versions of MySQL used a
COMMENToption for the connection string.DATA DIRECTORY,INDEX DIRECTORYBy using
DATA DIRECTORY='ordirectory'INDEX DIRECTORY='you can specify where thedirectory'MyISAMstorage engine should put a table's data file and index file. The directory must be the full path name to the directory, not a relative path.Important
Beginning with MySQL 6.0.4, table-level
DATA DIRECTORYandINDEX DIRECTORYoptions are ignored for partitioned tables. (Bug#32091)These options work only when you are not using the
--skip-symbolic-linksoption. Your operating system must also have a working, thread-saferealpath()call. See Section 7.6.1.2, “Using Symbolic Links for Tables on Unix”, for more complete information.If a
MyISAMtable is created with noDATA DIRECTORYoption, the.MYDfile is created in the database directory. By default, ifMyISAMfinds an existing.MYDfile in this case, it overwrites it. The same applies to.MYIfiles for tables created with noINDEX DIRECTORYoption. To suppress this behavior, start the server with the--keep_files_on_createoption, in which caseMyISAMwill not overwrite existing files and returns an error instead.If a
MyISAMtable is created with aDATA DIRECTORYorINDEX DIRECTORYoption and an existing.MYDor.MYIfile is found, MyISAM always returns an error. It will not overwrite a file in the specified directory.Important
Beginning with MySQL 6.0.5, you cannot use path names that contain the MySQL data directory with
DATA DIRECTORYorINDEX DIRECTORY. This includes partitioned tables and individual table partitions. (See Bug#32167.)DELAY_KEY_WRITESet this to 1 if you want to delay key updates for the table until the table is closed. See the description of the
delay_key_writesystem variable in Section 5.1.4, “Server System Variables”. (MyISAMonly.)INSERT_METHODIf you want to insert data into a
MERGEtable, you must specify withINSERT_METHODthe table into which the row should be inserted.INSERT_METHODis an option useful forMERGEtables only. Use a value ofFIRSTorLASTto have inserts go to the first or last table, or a value ofNOto prevent inserts. See Section 13.9, “TheMERGEStorage Engine”.KEY_BLOCK_SIZEThis option provides a hint to the storage engine about the size in bytes to use for index key blocks. The engine is allowed to change the value if necessary. A value of 0 indicates that the default value should be used. Individual index definitions can specify a
KEY_BLOCK_SIZEvalue of their own to override the table value.MAX_ROWSThe maximum number of rows you plan to store in the table. This is not a hard limit, but rather a hint to the storage engine that the table must be able to store at least this many rows.
MIN_ROWSThe minimum number of rows you plan to store in the table. The
MEMORYstorage engine uses this option as a hint about memory use.PACK_KEYSPACK_KEYStakes effect only withMyISAMtables. Set this option to 1 if you want to have smaller indexes. This usually makes updates slower and reads faster. Setting the option to 0 disables all packing of keys. Setting it toDEFAULTtells the storage engine to pack only longCHAR,VARCHAR,BINARY, orVARBINARYcolumns.If you do not use
PACK_KEYS, the default is to pack strings, but not numbers. If you usePACK_KEYS=1, numbers are packed as well.When packing binary number keys, MySQL uses prefix compression:
Every key needs one extra byte to indicate how many bytes of the previous key are the same for the next key.
The pointer to the row is stored in high-byte-first order directly after the key, to improve compression.
This means that if you have many equal keys on two consecutive rows, all following “same” keys usually only take two bytes (including the pointer to the row). Compare this to the ordinary case where the following keys takes
storage_size_for_key + pointer_size(where the pointer size is usually 4). Conversely, you get a significant benefit from prefix compression only if you have many numbers that are the same. If all keys are totally different, you use one byte more per key, if the key is not a key that can haveNULLvalues. (In this case, the packed key length is stored in the same byte that is used to mark if a key isNULL.)PASSWORDThis option is unused. If you have a need to scramble your
.frmfiles and make them unusable to any other MySQL server, please contact our sales department.RAID_TYPERAIDsupport has been removed as of MySQL 5.0. For information onRAID, seeCREATE TABLESyntax.ROW_FORMATDefines how the rows should be stored. For
MyISAMtables, the option value can beFIXEDorDYNAMICfor static or variable-length row format. myisampack sets the type toCOMPRESSED. See Section 13.5.3, “MyISAMTable Storage Formats”.For
InnoDBtables, rows are stored in compact format (ROW_FORMAT=COMPACT) by default. The noncompact format used in older versions of MySQL can still be requested by specifyingROW_FORMAT=REDUNDANT.Note
When executing a
CREATE TABLEstatement, if you specify a row format which is not supported by the storage engine that is used for the table, the table is created using that storage engine's default row format. The information reported in this column in response toSHOW TABLE STATUSis the actual row format used. This may differ from the value in theCreate_optionscolumn because the originalCREATE TABLEdefinition is retained during creation.UNIONis used when you want to access a collection of identicalMyISAMtables as one. This works only withMERGEtables. See Section 13.9, “TheMERGEStorage Engine”.You must have
SELECT,UPDATE, andDELETEprivileges for the tables you map to aMERGEtable.Note
Formerly, all tables used had to be in the same database as the
MERGEtable itself. This restriction no longer applies.
partition_options can be used to
control partitioning of the table created with
CREATE TABLE.
Important
Not all options shown in the syntax for
partition_options at the beginning of
this section are available for all partitioning types. Please
see the listings for the following individual types for
information specific to each type, and see
Chapter 17, Partitioning, for more complete information
about the workings of and uses for partitioning in MySQL, as
well as additional examples of table creation and other
statements relating to MySQL partitioning.
If used, a partition_options clause
begins with PARTITION BY. This clause contains
the function that is used to determine the partition; the function
returns an integer value ranging from 1 to
num, where
num is the number of partitions. (The
maximum number of user-defined partitions which a table may
contain is 1024; the number of subpartitions — discussed
later in this section — is included in this maximum.) The
choices that are available for this function in MySQL
6.0 are shown in the following list:
HASH(: Hashes one or more columns to create a key for placing and locating rows.expr)expris an expression using one or more table columns. This can be any legal MySQL expression (including MySQL functions) that yields a single integer value. For example, these are all validCREATE TABLEstatements usingPARTITION BY HASH:CREATE TABLE t1 (col1 INT, col2 CHAR(5)) PARTITION BY HASH(col1); CREATE TABLE t1 (col1 INT, col2 CHAR(5)) PARTITION BY HASH( ORD(col2) ); CREATE TABLE t1 (col1 INT, col2 CHAR(5), col3 DATETIME) PARTITION BY HASH ( YEAR(col3) );You may not use either
VALUES LESS THANorVALUES INclauses withPARTITION BY HASH.PARTITION BY HASHuses the remainder ofexprdivided by the number of partitions (that is, the modulus). For examples and additional information, see Section 17.2.3, “HASHPartitioning”.The
LINEARkeyword entails a somewhat different algorithm. In this case, the number of the partition in which a row is stored is calculated as the result of one or more logicalANDoperations. For discussion and examples of linear hashing, see Section 17.2.3.1, “LINEAR HASHPartitioning”.KEY(: This is similar tocolumn_list)HASH, except that MySQL supplies the hashing function so as to guarantee an even data distribution. Thecolumn_listargument is simply a list of table columns. This example shows a simple table partitioned by key, with 4 partitions:CREATE TABLE tk (col1 INT, col2 CHAR(5), col3 DATE) PARTITION BY KEY(col3) PARTITIONS 4;For tables that are partitioned by key, you can employ linear partitioning by using the
LINEARkeyword. This has the same effect as with tables that are partitioned byHASH. That is, the partition number is found using the&operator rather than the modulus (see Section 17.2.3.1, “LINEAR HASHPartitioning”, and Section 17.2.4, “KEYPartitioning”, for details). This example uses linear partitioning by key to distribute data between 5 partitions:CREATE TABLE tk (col1 INT, col2 CHAR(5), col3 DATE) PARTITION BY LINEAR KEY(col3) PARTITIONS 5;You may not use either
VALUES LESS THANorVALUES INclauses withPARTITION BY KEY.RANGE: In this case,exprshows a range of values using a set ofVALUES LESS THANoperators. When using range partitioning, you must define at least one partition usingVALUES LESS THAN. You cannot useVALUES INwith range partitioning.VALUES LESS THANcan be used with either a literal value or an expression that evaluates to a single value.Suppose that you have a table that you wish to partition on a column containing year values, according to the following scheme.
Partition Number: Years Range: 0 1990 and earlier 1 1991 – 1994 2 1995 – 1998 3 1999 – 2002 4 2003 – 2005 5 2006 and later A table implementing such a partitioning scheme can be realized by the
CREATE TABLEstatement shown here:CREATE TABLE t1 ( year_col INT, some_data INT ) PARTITION BY RANGE (year_col) ( PARTITION p0 VALUES LESS THAN (1991), PARTITION p1 VALUES LESS THAN (1995), PARTITION p2 VALUES LESS THAN (1999), PARTITION p3 VALUES LESS THAN (2002), PARTITION p4 VALUES LESS THAN (2006), PARTITION p5 VALUES LESS THAN MAXVALUE );PARTITION ... VALUES LESS THAN ...statements work in a consecutive fashion.VALUES LESS THAN MAXVALUEworks to specify “leftover” values that are greater than the maximum value otherwise specified.Note that
VALUES LESS THANclauses work sequentially in a manner similar to that of thecaseportions of aswitch ... caseblock (as found in many programming languages such as C, Java, and PHP). That is, the clauses must be arranged in such a way that the upper limit specified in each successiveVALUES LESS THANis greater than that of the previous one, with the one referencingMAXVALUEcoming last of all in the list.LIST(: This is useful when assigning partitions based on a table column with a restricted set of possible values, such as a state or country code. In such a case, all rows pertaining to a certain state or country can be assigned to a single partition, or a partition can be reserved for a certain set of states or countries. It is similar toexpr)RANGE, except that onlyVALUES INmay be used to specify allowable values for each partition.VALUES INis used with a list of values to be matched. For instance, you could create a partitioning scheme such as the following:CREATE TABLE client_firms ( id INT, name VARCHAR(35) ) PARTITION BY LIST (id) ( PARTITION r0 VALUES IN (1, 5, 9, 13, 17, 21), PARTITION r1 VALUES IN (2, 6, 10, 14, 18, 22), PARTITION r2 VALUES IN (3, 7, 11, 15, 19, 23), PARTITION r3 VALUES IN (4, 8, 12, 16, 20, 24) );When using list partitioning, you must define at least one partition using
VALUES IN. You cannot useVALUES LESS THANwithPARTITION BY LIST.Note
Currently, the value list used with
VALUES INmust consist of integer values only.The number of partitions may optionally be specified with a
PARTITIONSclause, wherenumnumis the number of partitions. If both this clause and anyPARTITIONclauses are used,nummust be equal to the total number of any partitions that are declared usingPARTITIONclauses.Note
Whether or not you use a
PARTITIONSclause in creating a table that is partitioned byRANGEorLIST, you must still include at least onePARTITION VALUESclause in the table definition (see below).A partition may optionally be divided into a number of subpartitions. This can be indicated by using the optional
SUBPARTITION BYclause. Subpartitioning may be done byHASHorKEY. Either of these may beLINEAR. These work in the same way as previously described for the equivalent partitioning types. (It is not possible to subpartition byLISTorRANGE.)The number of subpartitions can be indicated using the
SUBPARTITIONSkeyword followed by an integer value.Rigorous checking of the value used in
PARTITIONSorSUBPARTITIONSclauses is applied and this value must adhere to the following rules:The value must be a positive, nonzero integer.
No leading zeroes are permitted.
The value must be an integer literal, and cannot not be an expression. For example,
PARTITIONS 0.2E+01is not allowed, even though0.2E+01evaluates to2. (Bug#15890)
Note
The expression (expr) used in a
PARTITION BY clause cannot refer to any
columns not in the table being created, and attempting to do so
causes the statement to fail with an error. (Bug#29444)
Each partition may be individually defined using a
partition_definition clause. The
individual parts making up this clause are as follows:
PARTITION: This specifies a logical name for the partition.partition_nameA
VALUESclause: For range partitioning, each partition must include aVALUES LESS THANclause; for list partitioning, you must specify aVALUES INclause for each partition. This is used to determine which rows are to be stored in this partition. See the discussions of partitioning types in Chapter 17, Partitioning, for syntax examples.An optional
COMMENTclause may be used to specify a string that describes the partition. Example:COMMENT = 'Data for the years previous to 1999'
DATA DIRECTORYandINDEX DIRECTORYmay be used to indicate the directory where, respectively, the data and indexes for this partition are to be stored. Both theand thedata_dirmust be absolute system path names. Example:index_dirCREATE TABLE th (id INT, name VARCHAR(30), adate DATE) PARTITION BY LIST(YEAR(adate)) ( PARTITION p1999 VALUES IN (1995, 1999, 2003) DATA DIRECTORY = '/var/appdata/95/data' INDEX DIRECTORY = '/var/appdata/95/idx', PARTITION p2000 VALUES IN (1996, 2000, 2004) DATA DIRECTORY = '/var/appdata/96/data' INDEX DIRECTORY = '/var/appdata/96/idx', PARTITION p2001 VALUES IN (1997, 2001, 2005) DATA DIRECTORY = '/var/appdata/97/data' INDEX DIRECTORY = '/var/appdata/97/idx', PARTITION p2000 VALUES IN (1998, 2002, 2006) DATA DIRECTORY = '/var/appdata/98/data' INDEX DIRECTORY = '/var/appdata/98/idx' );DATA DIRECTORYandINDEX DIRECTORYbehave in the same way as in theCREATE TABLEstatement'stable_optionclause as used forMyISAMtables.One data directory and one index directory may be specified per partition. If left unspecified, the data and indexes are stored by default in the table's database directory.
On Windows, the
DATA DIRECTORYandINDEX DIRECTORYoptions are not supported for individual partitions or subpartitions. Beginning with MySQL 6.0.5, these options are ignored on Windows, except that a warning is generated. (Bug#30459)MAX_ROWSandMIN_ROWSmay be used to specify, respectively, the maximum and minimum number of rows to be stored in the partition. The values formax_number_of_rowsandmin_number_of_rowsmust be positive integers. As with the table-level options with the same names, these act only as “suggestions” to the server and are not hard limits.The optional
TABLESPACEclause may be used to designate a tablespace for the partition. Used forFalcononly.The partitioning handler accepts a
[STORAGE] ENGINEoption for bothPARTITIONandSUBPARTITION. Currently, the only way in which this can be used is to set all partitions or all subpartitions to the same storage engine, and an attempt to set different storage engines for partitions or subpartitions in the same table will give rise to the error ERROR 1469 (HY000): The mix of handlers in the partitions is not allowed in this version of MySQL. We expect to lift this restriction on partitioning in a future MySQL release.The partition definition may optionally contain one or more
subpartition_definitionclauses. Each of these consists at a minimum of theSUBPARTITION, wherenamenameis an identifier for the subpartition. Except for the replacement of thePARTITIONkeyword withSUBPARTITION, the syntax for a subpartition definition is identical to that for a partition definition.Subpartitioning must be done by
HASHorKEY, and can be done only onRANGEorLISTpartitions. See Section 17.2.5, “Subpartitioning”.
Partitions can be modified, merged, added to tables, and dropped
from tables. For basic information about the MySQL statements to
accomplish these tasks, see Section 12.1.6, “ALTER TABLE Syntax”. For
more detailed descriptions and examples, see
Section 17.3, “Partition Management”.
Important
The original CREATE TABLE
statement, including all specifications and table options are
stored by MySQL when the table is created. The information is
retained so that if you change storage engines, collations or
other settings using an ALTER
TABLE statement, the original table options specified
are retained. This allows you to change between
InnoDB and MyISAM table
types even though the row formats supported by the two engines
are different.
Because the text of the original statement is retained, but due
to the way that certain values and options may be silently
reconfigured (such as the ROW_FORMAT), the
active table definition (accessible through
DESCRIBE or with
SHOW TABLE STATUS) and the table
creation string (accessible through SHOW
CREATE TABLE) will report different values.
You can create one table from another by adding a
SELECT statement at the end of the
CREATE TABLE statement:
CREATE TABLEnew_tblSELECT * FROMorig_tbl;
MySQL creates new columns for all elements in the
SELECT. For example:
mysql>CREATE TABLE test (a INT NOT NULL AUTO_INCREMENT,->PRIMARY KEY (a), KEY(b))->ENGINE=MyISAM SELECT b,c FROM test2;
This creates a MyISAM table with three columns,
a, b, and
c. Notice that the columns from the
SELECT statement are appended to
the right side of the table, not overlapped onto it. Take the
following example:
mysql>SELECT * FROM foo;+---+ | n | +---+ | 1 | +---+ mysql>CREATE TABLE bar (m INT) SELECT n FROM foo;Query OK, 1 row affected (0.02 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql>SELECT * FROM bar;+------+---+ | m | n | +------+---+ | NULL | 1 | +------+---+ 1 row in set (0.00 sec)
For each row in table foo, a row is inserted in
bar with the values from foo
and default values for the new columns.
In a table resulting from
CREATE TABLE ...
SELECT, columns named only in the
CREATE TABLE part come first.
Columns named in both parts or only in the
SELECT part come after that. The
data type of SELECT columns can be
overridden by also specifying the column in the
CREATE TABLE part.
If any errors occur while copying the data to the table, it is automatically dropped and not created.
CREATE TABLE ...
SELECT does not automatically create any indexes for
you. This is done intentionally to make the statement as flexible
as possible. If you want to have indexes in the created table, you
should specify these before the
SELECT statement:
mysql> CREATE TABLE bar (UNIQUE (n)) SELECT n FROM foo;
Some conversion of data types might occur. For example, the
AUTO_INCREMENT attribute is not preserved, and
VARCHAR columns can become
CHAR columns. Retrained attributes
are NULL (or NOT NULL) and,
for those columns that have them, CHARACTER
SET, COLLATION,
COMMENT, and the DEFAULT
clause.
When creating a table with CREATE ... SELECT,
make sure to alias any function calls or expressions in the query.
If you do not, the CREATE statement might fail
or result in undesirable column names.
CREATE TABLE artists_and_works SELECT artist.name, COUNT(work.artist_id) AS number_of_works FROM artist LEFT JOIN work ON artist.id = work.artist_id GROUP BY artist.id;
You can also explicitly specify the data type for a generated column:
CREATE TABLE foo (a TINYINT NOT NULL) SELECT b+1 AS a FROM bar;
For CREATE TABLE ...
SELECT, if IF NOT EXISTS is given and
the table already exists, MySQL handles the statement as follows:
The table definition given in the
CREATE TABLEpart is ignored. No error occurs, even if the definition does not match that of the existing table.If there is a mismatch between the number of columns in the table and the number of columns produced by the
SELECTpart, the selected values are assigned to the rightmost columns. For example, if the table containsncolumns and theSELECTproducesmcolumns, wherem<n, the selected values are assigned to themrightmost columns in the table. Each of the initialn–mcolumns is assigned its default value, either that specified explicitly in the column definition or the implicit column data type default if the definition contains no default.If strict SQL mode is enabled and any of these initial columns do not have an explicit default value, the statement fails with an error.
The following example illustrates IF NOT EXISTS
handling:
mysql>CREATE TABLE t1 (i1 INT DEFAULT 0, i2 INT, i3 INT, i4 INT);Query OK, 0 rows affected (0.05 sec) mysql>CREATE TABLE IF NOT EXISTS t1 (c1 CHAR(10)) SELECT 1, 2;Query OK, 1 row affected, 1 warning (0.01 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql>SELECT * FROM t1;+------+------+------+------+ | i1 | i2 | i3 | i4 | +------+------+------+------+ | 0 | NULL | 1 | 2 | +------+------+------+------+ 1 row in set (0.00 sec)
Use LIKE to create an empty table based on the
definition of another table, including any column attributes and
indexes defined in the original table:
CREATE TABLEnew_tblLIKEorig_tbl;
The copy is created using the same version of the table storage
format as the original table. The
SELECT privilege is required on the
original table.
LIKE works only for base tables, not for views.
CREATE TABLE ... LIKE does not preserve any
DATA DIRECTORY or INDEX
DIRECTORY table options that were specified for the
original table, or any foreign key definitions.
You can precede the SELECT by
IGNORE or
REPLACE to indicate how to handle
rows that duplicate unique key values. With
IGNORE, new rows that duplicate an existing row
on a unique key value are discarded. With
REPLACE, new rows replace rows that
have the same unique key value. If neither
IGNORE nor
REPLACE is specified, duplicate
unique key values result in an error.
To ensure that the binary log can be used to re-create the
original tables, MySQL does not allow concurrent inserts during
CREATE TABLE ...
SELECT.
In some cases, MySQL silently changes column specifications from
those given in a CREATE TABLE or
ALTER TABLE statement. These
might be changes to a data type, to attributes associated with a
data type, or to an index specification.
TIMESTAMPcolumns areNOT NULLby default.Columns that are part of a
PRIMARY KEYare madeNOT NULLeven if not declared that way.Trailing spaces are automatically deleted from
ENUMandSETmember values when the table is created.MySQL maps certain data types used by other SQL database vendors to MySQL types. See Section 10.7, “Using Data Types from Other Database Engines”.
If you include a
USINGclause to specify an index type that is not legal for a given storage engine, but there is another index type available that the engine can use without affecting query results, the engine uses the available type.If strict SQL mode is not enabled, a
VARCHARcolumn with a length specification greater than 65535 is converted toTEXT, and aVARBINARYcolumn with a length specification greater than 65535 is converted toBLOB. Otherwise, an error occurs in either of these cases.Specifying the
CHARACTER SET binaryattribute for a character data type causes the column to be created as the corresponding binary data type:CHARbecomesBINARY,VARCHARbecomesVARBINARY, andTEXTbecomesBLOB. For theENUMandSETdata types, this does not occur; they are created as declared. Suppose that you specify a table using this definition:CREATE TABLE t ( c1 VARCHAR(10) CHARACTER SET binary, c2 TEXT CHARACTER SET binary, c3 ENUM('a','b','c') CHARACTER SET binary );The resulting table has this definition:
CREATE TABLE t ( c1 VARBINARY(10), c2 BLOB, c3 ENUM('a','b','c') CHARACTER SET binary );
To see whether MySQL used a data type other than the one you
specified, issue a DESCRIBE or
SHOW CREATE TABLE statement after
creating or altering the table.
Certain other data type changes can occur if you compress a table using myisampack. See Section 13.5.3.3, “Compressed Table Characteristics”.
CREATE
[DEFINER = { user | CURRENT_USER }]
TRIGGER trigger_name trigger_time trigger_event
ON tbl_name FOR EACH ROW trigger_stmt
This statement creates a new trigger. A trigger is a named
database object that is associated with a table, and that
activates when a particular event occurs for the table. The
trigger becomes associated with the table named
tbl_name, which must refer to a
permanent table. You cannot associate a trigger with a
TEMPORARY table or a view.
MySQL Enterprise For expert advice on creating triggers subscribe to the MySQL Enterprise Monitor. For more information, see http://www.mysql.com/products/enterprise/advisors.html.
CREATE TRIGGER requires the
TRIGGER privilege for the table
associated with the trigger.
The DEFINER clause determines the security
context to be used when checking access privileges at trigger
activation time.
trigger_time is the trigger action
time. It can be BEFORE or
AFTER to indicate that the trigger activates
before or after each row to be modified.
trigger_event indicates the kind of
statement that activates the trigger. The
trigger_event can be one of the
following:
INSERT: The trigger is activated whenever a new row is inserted into the table; for example, throughINSERT,LOAD DATA, andREPLACEstatements.UPDATE: The trigger is activated whenever a row is modified; for example, throughUPDATEstatements.DELETE: The trigger is activated whenever a row is deleted from the table; for example, throughDELETEandREPLACEstatements. However,DROP TABLEandTRUNCATEstatements on the table do not activate this trigger, because they do not useDELETE. Dropping a partition does not activateDELETEtriggers, either. See Section 12.2.11, “TRUNCATESyntax”.
It is important to understand that the
trigger_event does not represent a
literal type of SQL statement that activates the trigger so much
as it represents a type of table operation. For example, an
INSERT trigger is activated by not
only INSERT statements but also
LOAD DATA statements because both
statements insert rows into a table.
A potentially confusing example of this is the INSERT
INTO ... ON DUPLICATE KEY UPDATE ... syntax: a
BEFORE INSERT trigger will activate for every
row, followed by either an AFTER INSERT trigger
or both the BEFORE UPDATE and AFTER
UPDATE triggers, depending on whether there was a
duplicate key for the row.
There cannot be two triggers for a given table that have the same
trigger action time and event. For example, you cannot have two
BEFORE UPDATE triggers for a table. But you can
have a BEFORE UPDATE and a BEFORE
INSERT trigger, or a BEFORE UPDATE
and an AFTER UPDATE trigger.
trigger_stmt is the statement to
execute when the trigger activates. If you want to execute
multiple statements, use the BEGIN ... END
compound statement construct. This also enables you to use the
same statements that are allowable within stored routines. See
Section 12.8.1, “BEGIN ... END Compound Statement Syntax”. Some statements are not allowed in
triggers; see Section D.1, “Restrictions on Stored Routines, Triggers, and Events”.
MySQL stores the sql_mode system
variable setting that is in effect at the time a trigger is
created, and always executes the trigger with this setting in
force, regardless of the current server SQL
mode.
Note
Currently, triggers are not activated by cascaded foreign key actions. This limitation will be lifted as soon as possible.
In MySQL 6.0, you can write triggers containing
direct references to tables by name, such as the trigger named
testref shown in this example:
CREATE TABLE test1(a1 INT);
CREATE TABLE test2(a2 INT);
CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE test4(
a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
b4 INT DEFAULT 0
);
delimiter |
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END;
|
delimiter ;
INSERT INTO test3 (a3) VALUES
(NULL), (NULL), (NULL), (NULL), (NULL),
(NULL), (NULL), (NULL), (NULL), (NULL);
INSERT INTO test4 (a4) VALUES
(0), (0), (0), (0), (0), (0), (0), (0), (0), (0);
Suppose that you insert the following values into table
test1 as shown here:
mysql>INSERT INTO test1 VALUES->(1), (3), (1), (7), (1), (8), (4), (4);Query OK, 8 rows affected (0.01 sec) Records: 8 Duplicates: 0 Warnings: 0
As a result, the data in the four tables will be as follows:
mysql>SELECT * FROM test1;+------+ | a1 | +------+ | 1 | | 3 | | 1 | | 7 | | 1 | | 8 | | 4 | | 4 | +------+ 8 rows in set (0.00 sec) mysql>SELECT * FROM test2;+------+ | a2 | +------+ | 1 | | 3 | | 1 | | 7 | | 1 | | 8 | | 4 | | 4 | +------+ 8 rows in set (0.00 sec) mysql>SELECT * FROM test3;+----+ | a3 | +----+ | 2 | | 5 | | 6 | | 9 | | 10 | +----+ 5 rows in set (0.00 sec) mysql>SELECT * FROM test4;+----+------+ | a4 | b4 | +----+------+ | 1 | 3 | | 2 | 0 | | 3 | 1 | | 4 | 2 | | 5 | 0 | | 6 | 0 | | 7 | 1 | | 8 | 1 | | 9 | 0 | | 10 | 0 | +----+------+ 10 rows in set (0.00 sec)
You can refer to columns in the subject table (the table
associated with the trigger) by using the aliases
OLD and NEW.
OLD. refers
to a column of an existing row before it is updated or deleted.
col_nameNEW. refers
to the column of a new row to be inserted or an existing row after
it is updated.
col_name
The DEFINER clause specifies the MySQL account
to be used when checking access privileges at trigger activation
time. If a user value is given, it
should be a MySQL account in
'
format (the same format used in the
user_name'@'host_name'GRANT statement). The
user_name and
host_name values both are required. The
definer can also be given as
CURRENT_USER or
CURRENT_USER(). The default
DEFINER value is the user who executes the
CREATE TRIGGER statement. (This is
the same as DEFINER = CURRENT_USER.)
If you specify the DEFINER clause, these rules
determine the legal DEFINER user values:
If you do not have the
SUPERprivilege, the only legaluservalue is your own account, either specified literally or by usingCURRENT_USER. You cannot set the definer to some other account.If you have the
SUPERprivilege, you can specify any syntactically legal account name. If the account does not actually exist, a warning is generated.Although it is possible to create triggers with a nonexistent
DEFINERvalue, it is not a good idea for such triggers to be activated until the definer actually does exist. Otherwise, the behavior with respect to privilege checking is undefined.
MySQL takes the DEFINER user into account when
checking trigger privileges, as follows:
At
CREATE TRIGGERtime, the user who issues the statement must have theTRIGGERprivilege.At trigger activation time, privileges are checked against the
DEFINERuser. This user must have these privileges:The
TRIGGERprivilege.The
SELECTprivilege for the subject table if references to table columns occur viaOLD.orcol_nameNEW.in the trigger definition.col_nameThe
UPDATEprivilege for the subject table if table columns are targets ofSET NEW.assignments in the trigger definition.col_name=valueWhatever other privileges normally are required for the statements executed by the trigger.
Within a trigger, the
CURRENT_USER() function returns the
account used to check privileges at trigger activation time. This
is the DEFINER user, not the user whose actions
caused the trigger to be activated. For information about user
auditing within triggers, see
Section 5.5.9, “Auditing MySQL Account Activity”.
If you use LOCK TABLES to lock a
table that has triggers, the tables used within the trigger are
also locked, as described in
Section 12.4.5.2, “LOCK TABLES and Triggers”.
CREATE
[OR REPLACE]
[ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
[DEFINER = { user | CURRENT_USER }]
[SQL SECURITY { DEFINER | INVOKER }]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
The CREATE VIEW statement creates a
new view, or replaces an existing one if the OR
REPLACE clause is given. If the view does not exist,
CREATE OR REPLACE VIEW is the same as
CREATE VIEW. If the view does
exist, CREATE OR REPLACE VIEW is the same as
ALTER VIEW.
The select_statement is a
SELECT statement that provides the
definition of the view. (When you select from the view, you select
in effect using the SELECT
statement.) select_statement can select
from base tables or other views.
The view definition is “frozen” at creation time, so
changes to the underlying tables afterward do not affect the view
definition. For example, if a view is defined as SELECT
* on a table, new columns added to the table later do
not become part of the view.
The ALGORITHM clause affects how MySQL
processes the view. The DEFINER and
SQL SECURITY clauses specify the security
context to be used when checking access privileges at view
invocation time. The WITH CHECK OPTION clause
can be given to constrain inserts or updates to rows in tables
referenced by the view. These clauses are described later in this
section.
The CREATE VIEW statement requires
the CREATE VIEW privilege for the
view, and some privilege for each column selected by the
SELECT statement. For columns used
elsewhere in the SELECT statement
you must have the SELECT privilege.
If the OR REPLACE clause is present, you must
also have the DROP 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
db_name.view_name when you create it.
mysql> CREATE VIEW test.v AS SELECT * FROM t;
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
SELECT statement are used for the
view column names. To define explicit names for the view columns,
the optional column_list clause can be
given as a list of comma-separated identifiers. The number of
names in column_list must be the same
as the number of columns retrieved by the
SELECT statement.
Note
Prior to MySQL 6.0.8, When you modify an existing view, the
current view definition is backed up and saved. It is stored in
that table's database directory, in a subdirectory named
arc. The backup file for a view
v is named v.frm-00001.
If you alter the view again, the next backup is named
v.frm-00002. The three latest view backup
definitions are stored.
Backed up view definitions are not preserved by mysqldump, or any other such programs, but you can retain them using a file copy operation. However, they are not needed for anything but to provide you with a backup of your previous view definition.
It is safe to remove these backup definitions, but only while
mysqld is not running. If you delete the
arc subdirectory or its files while
mysqld is running, you will receive an error
the next time you try to alter the view:
mysql> ALTER VIEW v AS SELECT * FROM t; ERROR 6 (HY000): Error on delete of '.\test\arc/v.frm-0004' (Errcode: 2)
Columns retrieved by the SELECT
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
SELECT 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
SELECT statements. It can refer to
base tables or other views. It can use joins,
UNION, and subqueries. The
SELECT 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>CREATE TABLE t (qty INT, price INT);mysql>INSERT INTO t VALUES(3, 50);mysql>CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t;mysql>SELECT * FROM v;+------+-------+-------+ | qty | price | value | +------+-------+-------+ | 3 | 50 | 150 | +------+-------+-------+
A view definition is subject to the following restrictions:
The
SELECTstatement cannot contain a subquery in theFROMclause.The
SELECTstatement cannot refer to system or user variables.Within a stored program, the definition cannot refer to program parameters or local variables.
The
SELECTstatement cannot refer to prepared statement parameters.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
CHECK TABLEstatement.The definition cannot refer to a
TEMPORARYtable, and you cannot create aTEMPORARYview.Any tables named in the view definition must exist at definition time.
You cannot associate a trigger with a view.
As of MySQL 6.0.4, aliases for column names in the
SELECTstatement are checked against the maximum column length of 64 characters (not the maximum alias length of 256 characters).
ORDER BY is allowed in a view definition, but
it is ignored if you select from a view using a statement that has
its own ORDER BY.
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 LIMIT clause, and you select from
the view using a statement that has its own
LIMIT clause, it is undefined which limit
applies. This same principle applies to options such as
ALL, DISTINCT, or
SQL_SMALL_RESULT that follow the
SELECT keyword, and to clauses such
as INTO, FOR UPDATE,
LOCK IN SHARE MODE, and
PROCEDURE.
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>CREATE VIEW v (mycol) AS SELECT 'abc';Query OK, 0 rows affected (0.01 sec) mysql>SET sql_mode = '';Query OK, 0 rows affected (0.00 sec) mysql>SELECT "mycol" FROM v;+-------+ | mycol | +-------+ | mycol | +-------+ 1 row in set (0.01 sec) mysql>SET sql_mode = 'ANSI_QUOTES';Query OK, 0 rows affected (0.00 sec) mysql>SELECT "mycol" FROM v;+-------+ | mycol | +-------+ | abc | +-------+ 1 row in set (0.00 sec)
The DEFINER and SQL SECURITY
clauses determine which MySQL account to use when checking access
privileges for the view when a statement is executed that
references the view. The legal SQL SECURITY
characteristic values are DEFINER and
INVOKER. These indicate that the required
privileges must be held by the user who defined or invoked the
view, respectively. The default SQL SECURITY
value is DEFINER.
If a user value is given for the
DEFINER clause, it should be a MySQL account in
'
format (the same format used in the
user_name'@'host_name'GRANT statement). The
user_name and
host_name values both are required. The
definer can also be given as
CURRENT_USER or
CURRENT_USER(). The default
DEFINER value is the user who executes the
CREATE VIEW statement. This is the
same as specifying DEFINER = CURRENT_USER
explicitly.
If you specify the DEFINER clause, these rules
determine the legal DEFINER user values:
If you do not have the
SUPERprivilege, the only legaluservalue is your own account, either specified literally or by usingCURRENT_USER. You cannot set the definer to some other account.If you have the
SUPERprivilege, you can specify any syntactically legal account name. If the account does not actually exist, a warning is generated.If the
SQL SECURITYvalue isDEFINERbut the definer account does not exist when the view is referenced, an error occurs.
Within a view definition,
CURRENT_USER returns the view's
DEFINER value by default. For views defined
with the SQL SECURITY INVOKER characteristic,
CURRENT_USER returns the account
for the view's invoker. For information about user auditing within
views, see Section 5.5.9, “Auditing MySQL Account Activity”.
Within a stored routine that is defined with the SQL
SECURITY DEFINER characteristic,
CURRENT_USER returns the routine's
DEFINER value. This also affects a view defined
within such a program, if the view definition contains a
DEFINER value of
CURRENT_USER.
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 table columns, the creator must have privileges for the columns, as described previously. If the 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.
When a view is referenced, privileges for objects accessed by the view are checked against the privileges held by the view creator or invoker, depending on whether the
SQL SECURITYcharacteristic isDEFINERorINVOKER, respectively.If reference to a view causes execution of a stored function, privilege checking for statements executed within the function depend on whether the function is defined with a
SQL SECURITYcharacteristic ofDEFINERorINVOKER. If the security characteristic isDEFINER, the function runs with the privileges of its creator. If the characteristic isINVOKER, the function runs with the privileges determined by the view'sSQL SECURITYcharacteristic.
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 f():
CREATE VIEW v AS SELECT * FROM t WHERE t.id = f(t.name);
Suppose that f() 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
f() need to be checked when
f() executes. This might mean that privileges
are needed for p1() or p2(),
depending on the execution path within f().
Those privileges must be checked at runtime, and the user who must
possess the privileges is determined by the SQL
SECURITY values of the view v and the
function f().
The DEFINER and SQL SECURITY
clauses for views are extensions to standard SQL. In standard SQL,
views are handled using the rules for SQL SECURITY
INVOKER.
The optional ALGORITHM clause is a MySQL
extension to standard SQL. It affects how MySQL processes the
view. ALGORITHM takes three values:
MERGE, TEMPTABLE, or
UNDEFINED. The default algorithm is
UNDEFINED if no ALGORITHM
clause is present. For more information, see
Section 18.5.2, “View Processing Algorithms”.
Some views are updatable. That is, you can use them in statements
such as UPDATE,
DELETE, or
INSERT 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 nonupdatable.
The WITH CHECK OPTION clause can be given for
an updatable view to prevent inserts or updates to rows except
those for which the WHERE clause in the
select_statement is true.
In a WITH CHECK OPTION clause for an updatable
view, the LOCAL and CASCADED
keywords determine the scope of check testing when the view is
defined in terms of another view. The LOCAL
keyword restricts the CHECK OPTION only to the
view being defined. CASCADED causes the checks
for underlying views to be evaluated as well. When neither keyword
is given, the default is CASCADED.
For more information about updatable views and the WITH
CHECK OPTION clause, see
Section 18.5.3, “Updatable and Insertable Views”.
DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
DROP DATABASE drops all tables in
the database and deletes the database. Be
very careful with this statement! To use
DROP DATABASE, you need the
DROP privilege on the database.
DROP
SCHEMA is a synonym for DROP
DATABASE.
Important
When a database is dropped, user privileges on the database are
not automatically dropped. See
Section 12.5.1.3, “GRANT Syntax”.
IF EXISTS is used to prevent an error from
occurring if the database does not exist.
If you use DROP DATABASE on a
symbolically linked database, both the link and the original
database are deleted.
DROP DATABASE returns the number of
tables that were removed. This corresponds to the number of
.frm files removed.
The DROP DATABASE statement removes
from the given database directory those files and directories that
MySQL itself may create during normal operation:
All files with the following extensions.
.BAK.DAT.HSH.MRG.MYD.MYI.TRG.TRN.db.frm.ibd.ndb.parThe
db.optfile, if it exists.
If other files or directories remain in the database directory
after MySQL removes those just listed, the database directory
cannot be removed. In this case, you must remove any remaining
files or directories manually and issue the
DROP DATABASE statement again.
You can also drop databases with mysqladmin. See Section 4.5.2, “mysqladmin — Client for Administering a MySQL Server”.
DROP EVENT [IF EXISTS] event_name
This statement drops the event named
event_name. The event immediately
ceases being active, and is deleted completely from the server.
If the event does not exist, the error ERROR 1517
(HY000): Unknown event
'event_name' results. You
can override this and cause the statement to generate a warning
for nonexistent events instead using IF EXISTS.
This statement requires the EVENT
privilege for the schema to which the event to be dropped belongs.
The DROP FUNCTION statement is used
to drop stored functions and user-defined functions (UDFs):
For information about dropping stored functions, see Section 12.1.21, “
DROP PROCEDUREandDROP FUNCTIONSyntax”.For information about dropping user-defined functions, see Section 12.5.4.2, “
DROP FUNCTIONSyntax”.
DROP INDEXindex_nameONtbl_name
DROP INDEX drops the index named
index_name from the table
tbl_name. This statement is mapped to
an ALTER TABLE statement to drop
the index. See Section 12.1.6, “ALTER TABLE Syntax”.
Indexes on variable-width columns are dropped online; that is, dropping the indexes does not require any copying of the table. This is done automatically by the server whenever it determines that it is possible to do so; you do not have to use any special SQL syntax or server options to cause it to happen.
In standard MySQL 6.0 releases, it is not possible to
override the server when it determines that an index is to be
dropped online. For more information, see
Section 12.1.6, “ALTER TABLE Syntax”.
DROP {PROCEDURE | FUNCTION} [IF EXISTS] sp_name
This statement is used to drop a stored procedure or function.
That is, the specified routine is removed from the server. You
must have the ALTER ROUTINE
privilege for the routine. (That privilege is granted
automatically to the routine creator.)
The IF EXISTS clause is a MySQL extension. It
prevents an error from occurring if the procedure or function does
not exist. A warning is produced that can be viewed with
SHOW WARNINGS.
Prior to MySQL 6.0.10, DROP PROCEDURE IF EXISTS
and DROP FUNCTION IF EXISTS were not written to
the binary log if the stored procedure or function named in the
DROP statement did not exist on the master.
(Bug#13684)
DROP FUNCTION is also used to drop
user-defined functions (see Section 12.5.4.2, “DROP FUNCTION Syntax”).
DROP SERVER [ IF EXISTS ] server_name
Drops the server definition for the server named
. The
corresponding row within the server_namemysql.servers
table will be deleted. This statement requires the
SUPER privilege.
Dropping a server for a table does not affect any
FEDERATED tables that used this connection
information when they were created. See
Section 12.1.13, “CREATE SERVER Syntax”.
DROP SERVER does not cause an
automatic commit.
DROP [TEMPORARY] TABLE [IF EXISTS]
tbl_name [, tbl_name] ...
[RESTRICT | CASCADE]
DROP TABLE removes one or more
tables. You must have the DROP
privilege for each table. All table data and the table definition
are removed, so be
careful with this statement! If any of the tables named
in the argument list do not exist, MySQL returns an error
indicating by name which nonexisting tables it was unable to drop,
but it also drops all of the tables in the list that do exist.
Important
When a table is dropped, user privileges on the table are
not automatically dropped. See
Section 12.5.1.3, “GRANT Syntax”.
Note that for a partitioned table, DROP
TABLE permanently removes the table definition, all of
its partitions, and all of the data which was stored in those
partitions. It also removes the partitioning definition
(.par) file associated with the dropped
table.
Use IF EXISTS to prevent an error from
occurring for tables that do not exist. A NOTE
is generated for each nonexistent table when using IF
EXISTS. See Section 12.5.6.40, “SHOW WARNINGS Syntax”.
RESTRICT and CASCADE are
allowed to make porting easier. In MySQL 6.0, they do
nothing.
Note
DROP TABLE automatically commits
the current active transaction, unless you use the
TEMPORARY keyword.
The TEMPORARY keyword has the following
effects:
The statement drops only
TEMPORARYtables.The statement does not end an ongoing transaction.
No access rights are checked. (A
TEMPORARYtable is visible only to the session that created it, so no check is necessary.)
Using TEMPORARY is a good way to ensure that
you do not accidentally drop a non-TEMPORARY
table.
As of MySQL 6.0.3, DROP TABLE is
allowed only if you have acquired a WRITE lock
with LOCK TABLES, or if you hold no
locks, or if the table is a TEMPORARY table.
(Previously, if other tables were locked, you could drop a table
with a read lock or no lock, which could lead to deadlocks between
sessions. The current stricter behavior means that some usage
scenarios will fail when previously they did not.)
DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name
This statement drops a trigger. The schema (database) name is
optional. If the schema is omitted, the trigger is dropped from
the default schema. DROP TRIGGER
was added in MySQL 5.0.2. Its use requires the
TRIGGER privilege for the table
associated with the trigger.
Use IF EXISTS to prevent an error from
occurring for a trigger that does not exist. A
NOTE is generated for a nonexistent trigger
when using IF EXISTS. See
Section 12.5.6.40, “SHOW WARNINGS Syntax”.
Triggers for a table are also dropped if you drop the table.
DROP VIEW [IF EXISTS]
view_name [, view_name] ...
[RESTRICT | CASCADE]
DROP VIEW removes one or more
views. You must have the DROP
privilege for each view. If any of the views named in the argument
list do not exist, MySQL returns an error indicating by name which
nonexisting views it was unable to drop, but it also drops all of
the views in the list that do exist.
The IF EXISTS clause prevents an error from
occurring for views that don't exist. When this clause is given, a
NOTE is generated for each nonexistent view.
See Section 12.5.6.40, “SHOW WARNINGS Syntax”.
RESTRICT and CASCADE, if
given, are parsed and ignored.
RENAME TABLEtbl_nameTOnew_tbl_name[,tbl_name2TOnew_tbl_name2] ...
This statement renames one or more tables.
The rename operation is done atomically, which means that no other
session can access any of the tables while the rename is running.
For example, if you have an existing table
old_table, you can create another table
new_table that has the same structure but is
empty, and then replace the existing table with the empty one as
follows (assuming that backup_table does not
already exist):
CREATE TABLE new_table (...); RENAME TABLE old_table TO backup_table, new_table TO old_table;
If the statement renames more than one table, renaming operations
are done from left to right. If you want to swap two table names,
you can do so like this (assuming that
tmp_table does not already exist):
RENAME TABLE old_table TO tmp_table,
new_table TO old_table,
tmp_table TO new_table;
As long as two databases are on the same file system, you can use
RENAME TABLE to move a table from
one database to another:
RENAME TABLEcurrent_db.tbl_nameTOother_db.tbl_name;
If there are any triggers associated with a table which is moved
to a different database using RENAME
TABLE, then the statement fails with the error
Trigger in wrong schema.
RENAME TABLE also works for views,
as long as you do not try to rename a view into a different
database.
Any privileges granted specifically for the renamed table or view are not migrated to the new name. They must be changed manually.
When you execute RENAME, you cannot have any
locked tables or active transactions. You must also have the
ALTER and
DROP privileges on the original
table, and the CREATE and
INSERT privileges on the new table.
If MySQL encounters any errors in a multiple-table rename, it does a reverse rename for all renamed tables to return everything to its original state.
You cannot use RENAME to rename a
TEMPORARY table. However, you can use
ALTER TABLE instead:
mysql> ALTER TABLE orig_name RENAME new_name;
CALLsp_name([parameter[,...]]) CALLsp_name[()]
The CALL statement invokes a stored
procedure that was defined previously with
CREATE PROCEDURE.
Stored procedures that take no arguments can be invoked without
parentheses. That is, CALL p() and
CALL p are equivalent.
CALL can pass back values to its
caller using parameters that are declared as
OUT or INOUT parameters.
When the procedure returns, a client program can also obtain the
number of rows affected for the final statement executed within
the routine: At the SQL level, call the
ROW_COUNT() function; from the C
API, call the
mysql_affected_rows() function.
To get back a value from a procedure using an
OUT or INOUT parameter, pass
the parameter by means of a user variable, and then check the
value of the variable after the procedure returns. (If you are
calling the procedure from within another stored procedure or
function, you can also pass a routine parameter or local routine
variable as an IN or INOUT
parameter.) For an INOUT parameter, initialize
its value before passing it to the procedure. The following
procedure has an OUT parameter that the
procedure sets to the current server version, and an
INOUT value that the procedure increments by
one from its current value:
CREATE PROCEDURE p (OUT ver_param VARCHAR(25), INOUT incr_param INT) BEGIN # Set value of OUT parameter SELECT VERSION() INTO ver_param; # Increment value of INOUT parameter SET incr_param = incr_param + 1; END;
Before calling the procedure, initialize the variable to be passed
as the INOUT parameter. After calling the
procedure, the values of the two variables will have been set or
modified:
mysql>SET @increment = 10;mysql>CALL p(@version, @increment);mysql>SELECT @version, @increment;+------------------+------------+ | @version | @increment | +------------------+------------+ | 6.0.10-alpha-log | 11 | +------------------+------------+
In prepared CALL statements used
with PREPARE and
EXECUTE, placeholders can be used
for IN parameters. For OUT
and INOUT parameters, placeholder support is
available only as of MySQL 6.0.8. These types of parameters can be
used as follows:
mysql>SET @increment = 10;mysql>PREPARE s FROM 'CALL p(?, ?)';mysql>EXECUTE s USING @version, @increment;mysql>SELECT @version, @increment;+------------------+------------+ | @version | @increment | +------------------+------------+ | 6.0.10-alpha-log | 11 | +------------------+------------+
Before MySQL 6.0.8, placeholder support is not available for
OUT or INOUT parameters. To
work around this limitation for OUT and
INOUT parameters, forego the use of
placeholders; instead, refer to user variables in the
CALL statement itself and do not
specify them in the EXECUTE
statement:
mysql>SET @increment = 10;mysql>PREPARE s FROM 'CALL p(@version, @increment)';mysql>EXECUTE s;mysql>SELECT @version, @increment;+-----------------+------------+ | @version | @increment | +-----------------+------------+ | 6.0.7-alpha-log | 11 | +-----------------+------------+
To write C programs that use the
CALL SQL statement to execute
stored procedures that produce result sets, the
CLIENT_MULTI_RESULTS flag must be enabled. This
is because each CALL returns a
result to indicate the call status, in addition to any result sets
that might be returned by statements executed within the
procedure. CLIENT_MULTI_RESULTS must also be
enabled if CALL is used to execute
any stored procedure that contains prepared statements. It cannot
be determined when such a procedure is loaded whether those
statements will produce result sets, so it is necessary to assume
that they will.
CLIENT_MULTI_RESULTS can be enabled when you
call mysql_real_connect(), either
explicitly by passing the CLIENT_MULTI_RESULTS
flag itself, or implicitly by passing
CLIENT_MULTI_STATEMENTS (which also enables
CLIENT_MULTI_RESULTS). As of MySQL 6.0.8,
CLIENT_MULTI_RESULTS is enabled by default.
To process the result of a CALL
statement executed via
mysql_query() or
mysql_real_query(), use a loop
that calls mysql_next_result() to
determine whether there are more results. For an example, see
Section 20.10.12, “C API Support for Multiple Statement Execution”.
For programs written in a language that provides a MySQL
interface, there is no native method prior to MySQL 6.0.8 for
directly retrieving the results of OUT or
INOUT parameters from
CALL statements. To get the
parameter values, pass user-defined variables to the procedure in
the CALL statement and then execute
a SELECT statement to produce a
result set containing the variable values. To handle an
INOUT parameter, execute a statement prior to
the CALL that sets the
corresponding user variable to the value to be passed to the
procedure.
The following example illustrates the technique (without error
checking) for the stored procedure p described
earlier that has an OUT parameter and an
INOUT parameter:
mysql_query(mysql, "SET @increment = 10"); mysql_query(mysql, "CALL p(@version, @increment)"); mysql_query(mysql, "SELECT @version, @increment"); result = mysql_store_result(mysql); row = mysql_fetch_row(result); mysql_free_result(result);
After the preceding code executes, row[0] and
row[1] contain the values of
@version and @increment,
respectively.
As of MySQL 6.0.8, C programs can use the prepared-statement
interface to execute CALL
statements and access OUT and
INOUT parameters. This is done by processing
the result of a CALL statement
using a loop that calls
mysql_stmt_next_result() to
determine whether there are more results. For an example, see
Section 20.10.15, “C API Support for Prepared CALL
Statements”. Languages that
provide a MySQL interface can use prepared
CALL statements to directly
retrieve OUT and INOUT
procedure parameters.
Single-table syntax:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROMtbl_name[WHEREwhere_condition] [ORDER BY ...] [LIMITrow_count]
Multiple-table syntax:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
tbl_name[.*] [, tbl_name[.*]] ...
FROM table_references
[WHERE where_condition]
Or:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
FROM tbl_name[.*] [, tbl_name[.*]] ...
USING table_references
[WHERE where_condition]
For the single-table syntax, the
DELETE statement deletes rows from
tbl_name and returns a count of the
number of deleted rows. This count can be obtained by calling the
ROW_COUNT() function (see
Section 11.11.3, “Information Functions”). The
WHERE clause, if given, specifies the
conditions that identify which rows to delete. With no
WHERE clause, all rows are deleted. If the
ORDER BY clause is specified, the rows are
deleted in the order that is specified. The
LIMIT clause places a limit on the number of
rows that can be deleted.
For the multiple-table syntax,
DELETE deletes from each
tbl_name the rows that satisfy the
conditions. In this case, ORDER BY and
LIMIT cannot be used.
where_condition is an expression that
evaluates to true for each row to be deleted. It is specified as
described in Section 12.2.9, “SELECT Syntax”.
Currently, you cannot delete from a table and select from the same table in a subquery.
As stated, a DELETE statement with
no WHERE clause deletes all rows. A faster way
to do this, when you do not need to know the number of deleted
rows, is to use TRUNCATE
TABLE. However, within a transaction or if you have a
lock on the table,
TRUNCATE TABLE
cannot be used whereas DELETE can.
See Section 12.2.11, “TRUNCATE Syntax”, and Section 12.4.5, “LOCK TABLES and
UNLOCK
TABLES Syntax”.
If you delete the row containing the maximum value for an
AUTO_INCREMENT column, the value is not reused
for a MyISAM or InnoDB
table. If you delete all rows in the table with DELETE
FROM (without a
tbl_nameWHERE clause) in
autocommit mode, the sequence
starts over for all storage engines except
InnoDB and MyISAM. There are
some exceptions to this behavior for InnoDB
tables, as discussed in
Section 13.7.4.3, “AUTO_INCREMENT Handling in InnoDB”.
For MyISAM tables, you can specify an
AUTO_INCREMENT secondary column in a
multiple-column key. In this case, reuse of values deleted from
the top of the sequence occurs even for MyISAM
tables. See Section 3.6.9, “Using AUTO_INCREMENT”.
The DELETE statement supports the
following modifiers:
If you specify
LOW_PRIORITY, the server delays execution of theDELETEuntil no other clients are reading from the table. This affects only storage engines that use only table-level locking (MyISAM,MEMORY,MERGE).For
MyISAMtables, if you use theQUICKkeyword, the storage engine does not merge index leaves during delete, which may speed up some kinds of delete operations.The
IGNOREkeyword causes MySQL to ignore all errors during the process of deleting rows. (Errors encountered during the parsing stage are processed in the usual manner.) Errors that are ignored due to the use ofIGNOREare returned as warnings.
The speed of delete operations may also be affected by factors
discussed in Section 7.2.27, “Speed of DELETE Statements”.
In MyISAM tables, deleted rows are maintained
in a linked list and subsequent
INSERT operations reuse old row
positions. To reclaim unused space and reduce file sizes, use the
OPTIMIZE TABLE statement or the
myisamchk utility to reorganize tables.
OPTIMIZE TABLE is easier to use,
but myisamchk is faster. See
Section 12.5.2.4, “OPTIMIZE TABLE Syntax”, and Section 4.6.3, “myisamchk — MyISAM Table-Maintenance Utility”.
The QUICK modifier affects whether index leaves
are merged for delete operations. DELETE QUICK
is most useful for applications where index values for deleted
rows are replaced by similar index values from rows inserted
later. In this case, the holes left by deleted values are reused.
DELETE QUICK is not useful when deleted values
lead to underfilled index blocks spanning a range of index values
for which new inserts occur again. In this case, use of
QUICK can lead to wasted space in the index
that remains unreclaimed. Here is an example of such a scenario:
Create a table that contains an indexed
AUTO_INCREMENTcolumn.Insert many rows into the table. Each insert results in an index value that is added to the high end of the index.
Delete a block of rows at the low end of the column range using
DELETE QUICK.
In this scenario, the index blocks associated with the deleted
index values become underfilled but are not merged with other
index blocks due to the use of QUICK. They
remain underfilled when new inserts occur, because new rows do not
have index values in the deleted range. Furthermore, they remain
underfilled even if you later use
DELETE without
QUICK, unless some of the deleted index values
happen to lie in index blocks within or adjacent to the
underfilled blocks. To reclaim unused index space under these
circumstances, use OPTIMIZE TABLE.
If you are going to delete many rows from a table, it might be
faster to use DELETE QUICK followed by
OPTIMIZE TABLE. This rebuilds the
index rather than performing many index block merge operations.
The MySQL-specific LIMIT
option to
row_countDELETE tells the server the maximum
number of rows to be deleted before control is returned to the
client. This can be used to ensure that a given
DELETE statement does not take too
much time. You can simply repeat the
DELETE statement until the number
of affected rows is less than the LIMIT value.
If the DELETE statement includes an
ORDER BY clause, rows are deleted in the order
specified by the clause. This is useful primarily in conjunction
with LIMIT. For example, the following
statement finds rows matching the WHERE clause,
sorts them by timestamp_column, and deletes the
first (oldest) one:
DELETE FROM somelog WHERE user = 'jcole' ORDER BY timestamp_column LIMIT 1;
ORDER BY may also be useful in some cases to
delete rows in an order required to avoid referential integrity
violations.
If you are deleting many rows from a large table, you may exceed
the lock table size for an InnoDB table. To
avoid this problem, or simply to minimize the time that the table
remains locked, the following strategy (which does not use
DELETE at all) might be helpful:
Select the rows not to be deleted into an empty table that has the same structure as the original table:
INSERT INTO t_copy SELECT * FROM t WHERE ... ;
Use
RENAME TABLEto atomically move the original table out of the way and rename the copy to the original name:RENAME TABLE t TO t_old, t_copy TO t;
Drop the original table:
DROP TABLE t_old;
No other sessions can access the tables involved while
RENAME TABLE executes, so the
rename operation is not subject to concurrency problems. See
Section 12.1.26, “RENAME TABLE Syntax”.
You can specify multiple tables in a
DELETE statement to delete rows
from one or more tables depending on the particular condition in
the WHERE clause. However, you cannot use
ORDER BY or LIMIT in a
multiple-table DELETE. The
table_references clause lists the
tables involved in the join. Its syntax is described in
Section 12.2.9.1, “JOIN Syntax”.
For the first multiple-table syntax, only matching rows from the
tables listed before the FROM clause are
deleted. For the second multiple-table syntax, only matching rows
from the tables listed in the FROM clause
(before the USING clause) are deleted. The
effect is that you can delete rows from many tables at the same
time and have additional tables that are used only for searching:
DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id;
Or:
DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id;
These statements use all three tables when searching for rows to
delete, but delete matching rows only from tables
t1 and t2.
The preceding examples use INNER JOIN, but
multiple-table DELETE statements
can use other types of join allowed in
SELECT statements, such as
LEFT JOIN. For example, to delete rows that
exist in t1 that have no match in
t2, use a LEFT JOIN:
DELETE t1 FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL;
The syntax allows .* after each
tbl_name for compatibility with
Access.
If you use a multiple-table DELETE
statement involving InnoDB tables for which
there are foreign key constraints, the MySQL optimizer might
process tables in an order that differs from that of their
parent/child relationship. In this case, the statement fails and
rolls back. Instead, you should delete from a single table and
rely on the ON DELETE capabilities that
InnoDB provides to cause the other tables to be
modified accordingly.
Note
If you declare an alias for a table, you must use the alias when referring to the table:
DELETE t1 FROM test AS t1, test2 WHERE ...
Table aliases in a multiple-table
DELETE statement should be declared
only in the table_references part.
Elsewhere in the statement, alias references are allowed but not
alias declarations.
Correct:
DELETE a1, a2 FROM t1 AS a1 INNER JOIN t2 AS a2 WHERE a1.id=a2.id; DELETE FROM a1, a2 USING t1 AS a1 INNER JOIN t2 AS a2 WHERE a1.id=a2.id;
Incorrect:
DELETE t1 AS a1, t2 AS a2 FROM t1 INNER JOIN t2 WHERE a1.id=a2.id; DELETE FROM t1 AS a1, t2 AS a2 USING t1 INNER JOIN t2 WHERE a1.id=a2.id;
Declaration of aliases other than in the
table_references part can lead to
ambiguous statements that have unexpected results such as deleting
rows from the wrong table. This is such a statement:
DELETE FROM t1 AS a2 USING t1 AS a1 INNER JOIN t2 AS a2;
Before MySQL 6.0.5, alias declarations are allowed in other than
the table_references part, but should
be avoided for the reason just mentioned.
Cross-database deletes are supported for multiple-table deletes,
but you should be aware that in the list of tables from which to
delete rows, aliases will have a default database unless one is
specified explicitly. For example, if the current database is
test, the following statement does not work
because the unqualified alias a1 has a default
database of test:
DELETE a1, a2 FROM db1.t1 AS a1 INNER JOIN db2.t2 AS a2 WHERE a1.id=a2.id;
To correctly match the alias, you must explicitly qualify it with the database of the table being aliased:
DELETE db1.a1, db2.a2 FROM db1.t1 AS a1 INNER JOIN db2.t2 AS a2 WHERE a1.id=a2.id;
DOexpr[,expr] ...
DO executes the expressions but
does not return any results. In most respects,
DO is shorthand for SELECT
, but has the
advantage that it is slightly faster when you do not care about
the result.
expr, ...
DO is useful primarily with
functions that have side effects, such as
RELEASE_LOCK().
HANDLERtbl_nameOPEN [ [AS]alias] HANDLERtbl_nameREADindex_name{ = | >= | <= | < } (value1,value2,...) [ WHEREwhere_condition] [LIMIT ... ] HANDLERtbl_nameREADindex_name{ FIRST | NEXT | PREV | LAST } [ WHEREwhere_condition] [LIMIT ... ] HANDLERtbl_nameREAD { FIRST | NEXT } [ WHEREwhere_condition] [LIMIT ... ] HANDLERtbl_nameCLOSE
The HANDLER statement provides
direct access to table storage engine interfaces. It is available
for MyISAM and InnoDB
tables.
The HANDLER ... OPEN statement opens a table,
making it accessible via subsequent HANDLER ...
READ statements. This table object is not shared by
other sessions and is not closed until the session calls
HANDLER ... CLOSE or the session terminates. If
you open the table using an alias, further references to the open
table with other HANDLER statements
must use the alias rather than the table name.
The first HANDLER ... READ syntax fetches a row
where the index specified satisfies the given values and the
WHERE condition is met. If you have a
multiple-column index, specify the index column values as a
comma-separated list. Either specify values for all the columns in
the index, or specify values for a leftmost prefix of the index
columns. Suppose that an index my_idx includes
three columns named col_a,
col_b, and col_c, in that
order. The HANDLER statement can
specify values for all three columns in the index, or for the
columns in a leftmost prefix. For example:
HANDLER ... READ my_idx = (col_a_val,col_b_val,col_c_val) ... HANDLER ... READ my_idx = (col_a_val,col_b_val) ... HANDLER ... READ my_idx = (col_a_val) ...
To employ the HANDLER interface to
refer to a table's PRIMARY KEY, use the quoted
identifier `PRIMARY`:
HANDLER tbl_name READ `PRIMARY` ...
The second HANDLER ... READ syntax fetches a
row from the table in index order that matches the
WHERE condition.
The third HANDLER ... READ syntax fetches a row
from the table in natural row order that matches the
WHERE condition. It is faster than
HANDLER when a full table
scan is desired. Natural row order is the order in which rows are
stored in a tbl_name READ
index_nameMyISAM table data file. This
statement works for InnoDB tables as well, but
there is no such concept because there is no separate data file.
Without a LIMIT clause, all forms of
HANDLER ... READ fetch a single row if one is
available. To return a specific number of rows, include a
LIMIT clause. It has the same syntax as for the
SELECT statement. See
Section 12.2.9, “SELECT Syntax”.
HANDLER ... CLOSE closes a table that was
opened with HANDLER ... OPEN.
There are several reasons to use the
HANDLER interface instead of normal
SELECT statements:
HANDLERis faster thanSELECT:A designated storage engine handler object is allocated for the
HANDLER ... OPEN. The object is reused for subsequentHANDLERstatements for that table; it need not be reinitialized for each one.There is less parsing involved.
There is no optimizer or query-checking overhead.
The table does not have to be locked between two handler requests.
The handler interface does not have to provide a consistent look of the data (for example, dirty reads are allowed), so the storage engine can use optimizations that
SELECTdoes not normally allow.
For applications that use a low-level
ISAM-like interface,HANDLERmakes it much easier to port them to MySQL.HANDLERenables you to traverse a database in a manner that is difficult (or even impossible) to accomplish withSELECT. TheHANDLERinterface is a more natural way to look at data when working with applications that provide an interactive user interface to the database.
HANDLER is a somewhat low-level
statement. For example, it does not provide consistency. That is,
HANDLER ... OPEN does not
take a snapshot of the table, and does not
lock the table. This means that after a HANDLER ...
OPEN statement is issued, table data can be modified (by
the current session or other sessions) and these modifications
might be only partially visible to HANDLER ...
NEXT or HANDLER ... PREV scans.
An open handler can be closed and marked for reopen, in which case the handler loses its position in the table. This occurs when both of the following circumstances are true:
Any session executes
FLUSH TABLESor DDL statements on the handler's table.The session in which the handler is open executes non-
HANDLERstatements that use tables.
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
Or:
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
Or:
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
INSERT inserts new rows into an
existing table. The INSERT
... VALUES and
INSERT ... SET
forms of the statement insert rows based on explicitly specified
values. The INSERT
... SELECT form inserts rows selected from another table
or tables. INSERT
... SELECT is discussed further in
Section 12.2.5.1, “INSERT ...
SELECT Syntax”.
You can use REPLACE instead of
INSERT to overwrite old rows.
REPLACE is the counterpart to
INSERT IGNORE in
the treatment of new rows that contain unique key values that
duplicate old rows: The new rows are used to replace the old rows
rather than being discarded. See Section 12.2.8, “REPLACE Syntax”.
tbl_name is the table into which rows
should be inserted. The columns for which the statement provides
values can be specified as follows:
You can provide a comma-separated list of column names following the table name. In this case, a value for each named column must be provided by the
VALUESlist or theSELECTstatement.If you do not specify a list of column names for
INSERT ... VALUESorINSERT ... SELECT, values for every column in the table must be provided by theVALUESlist or theSELECTstatement. If you do not know the order of the columns in the table, useDESCRIBEto find out.tbl_nameThe
SETclause indicates the column names explicitly.
Column values can be given in several ways:
If you are not running in strict SQL mode, any column not explicitly given a value is set to its default (explicit or implicit) value. For example, if you specify a column list that does not name all the columns in the table, unnamed columns are set to their default values. Default value assignment is described in Section 10.1.4, “Data Type Default Values”. See also Section 1.7.6.2, “Constraints on Invalid Data”.
If you want an
INSERTstatement to generate an error unless you explicitly specify values for all columns that do not have a default value, you should use strict mode. See Section 5.1.8, “Server SQL Modes”.Use the keyword
DEFAULTto set a column explicitly to its default value. This makes it easier to writeINSERTstatements that assign values to all but a few columns, because it enables you to avoid writing an incompleteVALUESlist that does not include a value for each column in the table. Otherwise, you would have to write out the list of column names corresponding to each value in theVALUESlist.You can also use
DEFAULT(as a more general form that can be used in expressions to produce a given column's default value.col_name)If both the column list and the
VALUESlist are empty,INSERTcreates a row with each column set to its default value:INSERT INTO
tbl_name() VALUES();In strict mode, an error occurs if any column doesn't have a default value. Otherwise, MySQL uses the implicit default value for any column that does not have an explicitly defined default.
You can specify an expression
exprto provide a column value. This might involve type conversion if the type of the expression does not match the type of the column, and conversion of a given value can result in different inserted values depending on the data type. For example, inserting the string'1999.0e-2'into anINT,FLOAT,DECIMAL(10,6), orYEARcolumn results in the values1999,19.9921,19.992100, and1999being inserted, respectively. The reason the value stored in theINTandYEARcolumns is1999is that the string-to-integer conversion looks only at as much of the initial part of the string as may be considered a valid integer or year. For the floating-point and fixed-point columns, the string-to-floating-point conversion considers the entire string a valid floating-point value.An expression
exprcan refer to any column that was set earlier in a value list. For example, you can do this because the value forcol2refers tocol1, which has previously been assigned:INSERT INTO
tbl_name(col1,col2) VALUES(15,col1*2);But the following is not legal, because the value for
col1refers tocol2, which is assigned aftercol1:INSERT INTO
tbl_name(col1,col2) VALUES(col2*2,15);One exception involves columns that contain
AUTO_INCREMENTvalues. Because theAUTO_INCREMENTvalue is generated after other value assignments, any reference to anAUTO_INCREMENTcolumn in the assignment returns a0.
INSERT statements that use
VALUES syntax can insert multiple rows. To do
this, include multiple lists of column values, each enclosed
within parentheses and separated by commas. Example:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
The values list for each row must be enclosed within parentheses. The following statement is illegal because the number of values in the list does not match the number of column names:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3,4,5,6,7,8,9);
VALUE is a synonym for
VALUES in this context. Neither implies
anything about the number of values lists, and either may be used
whether there is a single values list or multiple lists.
The affected-rows value for an
INSERT can be obtained using the
ROW_COUNT() function (see
Section 11.11.3, “Information Functions”), or the
mysql_affected_rows() C API
function (see Section 20.10.3.1, “mysql_affected_rows()”).
If you use an INSERT ...
VALUES statement with multiple value lists or
INSERT ...
SELECT, the statement returns an information string in
this format:
Records: 100 Duplicates: 0 Warnings: 0
Records indicates the number of rows processed
by the statement. (This is not necessarily the number of rows
actually inserted because Duplicates can be
nonzero.) Duplicates indicates the number of
rows that could not be inserted because they would duplicate some
existing unique index value. Warnings indicates
the number of attempts to insert column values that were
problematic in some way. Warnings can occur under any of the
following conditions:
Inserting
NULLinto a column that has been declaredNOT NULL. For multiple-rowINSERTstatements orINSERT INTO ... SELECTstatements, the column is set to the implicit default value for the column data type. This is0for numeric types, the empty string ('') for string types, and the “zero” value for date and time types.INSERT INTO ... SELECTstatements are handled the same way as multiple-row inserts because the server does not examine the result set from theSELECTto see whether it returns a single row. (For a single-rowINSERT, no warning occurs whenNULLis inserted into aNOT NULLcolumn. Instead, the statement fails with an error.)Setting a numeric column to a value that lies outside the column's range. The value is clipped to the closest endpoint of the range.
Assigning a value such as
'10.34 a'to a numeric column. The trailing nonnumeric text is stripped off and the remaining numeric part is inserted. If the string value has no leading numeric part, the column is set to0.Inserting a string into a string column (
CHAR,VARCHAR,TEXT, orBLOB) that exceeds the column's maximum length. The value is truncated to the column's maximum length.Inserting a value into a date or time column that is illegal for the data type. The column is set to the appropriate zero value for the type.
If you are using the C API, the information string can be obtained
by invoking the mysql_info()
function. See Section 20.10.3.35, “mysql_info()”.
If INSERT inserts a row into a
table that has an AUTO_INCREMENT column, you
can find the value used for that column by using the SQL
LAST_INSERT_ID() function. From
within the C API, use the
mysql_insert_id() function.
However, you should note that the two functions do not always
behave identically. The behavior of
INSERT statements with respect to
AUTO_INCREMENT columns is discussed further in
Section 11.11.3, “Information Functions”, and
Section 20.10.3.37, “mysql_insert_id()”.
The INSERT statement supports the
following modifiers:
If you use the
DELAYEDkeyword, the server puts the row or rows to be inserted into a buffer, and the client issuing theINSERT DELAYEDstatement can then continue immediately. If the table is in use, the server holds the rows. When the table is free, the server begins inserting rows, checking periodically to see whether there are any new read requests for the table. If there are, the delayed row queue is suspended until the table becomes free again. See Section 12.2.5.2, “INSERT DELAYEDSyntax”.DELAYEDis ignored withINSERT ... SELECTorINSERT ... ON DUPLICATE KEY UPDATE.DELAYEDis also disregarded for anINSERTthat uses functions accessing tables or triggers, or that is called from a function or a trigger.If you use the
LOW_PRIORITYkeyword, execution of theINSERTis delayed until no other clients are reading from the table. This includes other clients that began reading while existing clients are reading, and while theINSERT LOW_PRIORITYstatement is waiting. It is possible, therefore, for a client that issues anINSERT LOW_PRIORITYstatement to wait for a very long time (or even forever) in a read-heavy environment. (This is in contrast toINSERT DELAYED, which lets the client continue at once. Note thatLOW_PRIORITYshould normally not be used withMyISAMtables because doing so disables concurrent inserts. See Section 7.3.3, “Concurrent Inserts”.If you specify
HIGH_PRIORITY, it overrides the effect of the--low-priority-updatesoption if the server was started with that option. It also causes concurrent inserts not to be used. See Section 7.3.3, “Concurrent Inserts”.LOW_PRIORITYandHIGH_PRIORITYaffect only storage engines that use only table-level locking (MyISAM,MEMORY,MERGE).If you use the
IGNOREkeyword, errors that occur while executing theINSERTstatement are treated as warnings instead. For example, withoutIGNORE, a row that duplicates an existingUNIQUEindex orPRIMARY KEYvalue in the table causes a duplicate-key error and the statement is aborted. WithIGNORE, the row still is not inserted, but no error is issued.IGNOREhas a similar effect on inserts into partitioned tables where no partition matching a given value is found. WithoutIGNORE, suchINSERTstatements are aborted with an error; however, whenINSERT IGNOREis used, the insert operation fails silently for the row containing the unmatched value, but any rows that are matched are inserted. For an example, see Section 17.2.2, “LISTPartitioning”.Data conversions that would trigger errors abort the statement if
IGNOREis not specified. WithIGNORE, invalid values are adjusted to the closest values and inserted; warnings are produced but the statement does not abort. You can determine with themysql_info()C API function how many rows were actually inserted into the table.If you specify
ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in aUNIQUEindex orPRIMARY KEY, anUPDATEof the old row is performed. The affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated. See Section 12.2.5.3, “INSERT ... ON DUPLICATE KEY UPDATESyntax”.
Inserting into a table requires the
INSERT privilege for the table. If
the ON DUPLICATE KEY UPDATE clause is used and
a duplicate key causes an UPDATE to
be performed instead, the statement requires the
UPDATE privilege for the columns to
be updated. For columns that are read but not modified you need
only the SELECT privilege (such as
for a column referenced only on the right hand side of an
col_name=expr
assignment in an ON DUPLICATE KEY UPDATE
clause).
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
With INSERT ...
SELECT, you can quickly insert many rows into a table
from one or many tables. For example:
INSERT INTO tbl_temp2 (fld_id) SELECT tbl_temp1.fld_order_id FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
The following conditions hold for a
INSERT ...
SELECT statements:
Specify
IGNOREto ignore rows that would cause duplicate-key violations.DELAYEDis ignored withINSERT ... SELECT.The target table of the
INSERTstatement may appear in theFROMclause of theSELECTpart of the query. (This was not possible in some older versions of MySQL.) In this case, MySQL creates a temporary table to hold the rows from theSELECTand then inserts those rows into the target table. However, it remains true that you cannot useINSERT INTO t ... SELECT ... FROM twhentis aTEMPORARYtable, becauseTEMPORARYtables cannot be referred to twice in the same statement (see Section B.1.7.3, “TEMPORARYTable Problems”).AUTO_INCREMENTcolumns work as usual.To ensure that the binary log can be used to re-create the original tables, MySQL does not allow concurrent inserts for
INSERT ... SELECTstatements.Currently, you cannot insert into a table and select from the same table in a subquery.
To avoid ambiguous column reference problems when the
SELECTand theINSERTrefer to the same table, provide a unique alias for each table used in theSELECTpart, and qualify column names in that part with the appropriate alias.
In the values part of ON DUPLICATE KEY
UPDATE, you can refer to columns in other tables, as
long as you do not use GROUP BY in the
SELECT part. One side effect is
that you must qualify nonunique column names in the values part.
INSERT DELAYED ...
The DELAYED option for the
INSERT statement is a MySQL
extension to standard SQL that is very useful if you have
clients that cannot or need not wait for the
INSERT to complete. This is a
common situation when you use MySQL for logging and you also
periodically run SELECT and
UPDATE statements that take a
long time to complete.
When a client uses INSERT
DELAYED, it gets an okay from the server at once, and
the row is queued to be inserted when the table is not in use by
any other thread.
Another major benefit of using INSERT
DELAYED is that inserts from many clients are bundled
together and written in one block. This is much faster than
performing many separate inserts.
Note that INSERT DELAYED is
slower than a normal INSERT if
the table is not otherwise in use. There is also the additional
overhead for the server to handle a separate thread for each
table for which there are delayed rows. This means that you
should use INSERT DELAYED only
when you are really sure that you need it.
The queued rows are held only in memory until they are inserted
into the table. This means that if you terminate
mysqld forcibly (for example, with
kill -9) or if mysqld dies
unexpectedly, any queued rows that have not been
written to disk are lost.
There are some constraints on the use of
DELAYED:
INSERT DELAYEDworks only withMyISAM,MEMORY,ARCHIVE, andBLACKHOLEtables. For engines that do not supportDELAYED, an error occurs.An error occurs for
INSERT DELAYEDif used with a table that has been locked withLOCK TABLESbecause the insert must be handled by a separate thread, not by the session that holds the lock.For
MyISAMtables, if there are no free blocks in the middle of the data file, concurrentSELECTandINSERTstatements are supported. Under these circumstances, you very seldom need to useINSERT DELAYEDwithMyISAM.INSERT DELAYEDshould be used only forINSERTstatements that specify value lists. The server ignoresDELAYEDforINSERT ... SELECTorINSERT ... ON DUPLICATE KEY UPDATEstatements.Because the
INSERT DELAYEDstatement returns immediately, before the rows are inserted, you cannot useLAST_INSERT_ID()to get theAUTO_INCREMENTvalue that the statement might generate.DELAYEDrows are not visible toSELECTstatements until they actually have been inserted.INSERT DELAYEDis treated as a normalINSERTif the statement inserts multiple rows and binary logging is enabled and the global logging format is to use statement-based logging (binlog_formatis set toSTATEMENT). This restriction does not apply to row-based binary logging.DELAYEDis ignored on slave replication servers, so thatINSERT DELAYEDis treated as a normalINSERTon slaves. This is becauseDELAYEDcould cause the slave to have different data than the master.Pending
INSERT DELAYEDstatements are lost if a table is write locked andALTER TABLEis used to modify the table structure.INSERT DELAYEDis not supported for views.INSERT DELAYEDis not supported for partitioned tables.
The following describes in detail what happens when you use the
DELAYED option to
INSERT or
REPLACE. In this description, the
“thread” is the thread that received an
INSERT DELAYED statement and
“handler” is the thread that handles all
INSERT DELAYED statements for a
particular table.
When a thread executes a
DELAYEDstatement for a table, a handler thread is created to process allDELAYEDstatements for the table, if no such handler already exists.The thread checks whether the handler has previously acquired a
DELAYEDlock; if not, it tells the handler thread to do so. TheDELAYEDlock can be obtained even if other threads have aREADorWRITElock on the table. However, the handler waits for allALTER TABLElocks orFLUSH TABLESstatements to finish, to ensure that the table structure is up to date.The thread executes the
INSERTstatement, but instead of writing the row to the table, it puts a copy of the final row into a queue that is managed by the handler thread. Any syntax errors are noticed by the thread and reported to the client program.The client cannot obtain from the server the number of duplicate rows or the
AUTO_INCREMENTvalue for the resulting row, because theINSERTreturns before the insert operation has been completed. (If you use the C API, themysql_info()function does not return anything meaningful, for the same reason.)The binary log is updated by the handler thread when the row is inserted into the table. In case of multiple-row inserts, the binary log is updated when the first row is inserted.
Each time that
delayed_insert_limitrows are written, the handler checks whether anySELECTstatements are still pending. If so, it allows these to execute before continuing.When the handler has no more rows in its queue, the table is unlocked. If no new
INSERT DELAYEDstatements are received withindelayed_insert_timeoutseconds, the handler terminates.If more than
delayed_queue_sizerows are pending in a specific handler queue, the thread requestingINSERT DELAYEDwaits until there is room in the queue. This is done to ensure that mysqld does not use all memory for the delayed memory queue.The handler thread shows up in the MySQL process list with
delayed_insertin theCommandcolumn. It is killed if you execute aFLUSH TABLESstatement or kill it withKILL. However, before exiting, it first stores all queued rows into the table. During this time it does not accept any newthread_idINSERTstatements from other threads. If you execute anINSERT DELAYEDstatement after this, a new handler thread is created.Note that this means that
INSERT DELAYEDstatements have higher priority than normalINSERTstatements if there is anINSERT DELAYEDhandler running. Other update statements have to wait until theINSERT DELAYEDqueue is empty, someone terminates the handler thread (withKILL), or someone executes athread_idFLUSH TABLES.The following status variables provide information about
INSERT DELAYEDstatements.Status Variable Meaning Delayed_insert_threadsNumber of handler threads Delayed_writesNumber of rows written with INSERT DELAYEDNot_flushed_delayed_rowsNumber of rows waiting to be written You can view these variables by issuing a
SHOW STATUSstatement or by executing a mysqladmin extended-status command.
If you specify ON DUPLICATE KEY UPDATE, and a
row is inserted that would cause a duplicate value in a
UNIQUE index or PRIMARY
KEY, an UPDATE of the
old row is performed. For example, if column
a is declared as UNIQUE
and contains the value 1, the following two
statements have identical effect:
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1; UPDATE table SET c=c+1 WHERE a=1;
With ON DUPLICATE KEY UPDATE, the
affected-rows value per row is 1 if the row is inserted as a new
row and 2 if an existing row is updated.
If column b is also unique, the
INSERT is equivalent to this
UPDATE statement instead:
UPDATE table SET c=c+1 WHERE a=1 OR b=2 LIMIT 1;
If a=1 OR b=2 matches several rows, only
one row is updated. In general, you should
try to avoid using an ON DUPLICATE KEY UPDATE
clause on tables with multiple unique indexes.
The ON DUPLICATE KEY UPDATE clause can
contain multiple column assignments, separated by commas.
You can use the
VALUES(
function in the col_name)UPDATE clause to
refer to column values from the
INSERT portion of the
INSERT ...
ON DUPLICATE KEY UPDATE statement. In other words,
VALUES(
in the col_name)ON DUPLICATE KEY UPDATE clause refers
to the value of col_name that would
be inserted, had no duplicate-key conflict occurred. This
function is especially useful in multiple-row inserts. The
VALUES() function is meaningful
only in INSERT ... UPDATE statements and
returns NULL otherwise. Example:
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
That statement is identical to the following two statements:
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=3; INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;
If a table contains an AUTO_INCREMENT column
and INSERT
... ON DUPLICATE KEY UPDATE inserts or updates a row,
the LAST_INSERT_ID() function
returns the AUTO_INCREMENT value.
The DELAYED option is ignored when you use
ON DUPLICATE KEY UPDATE.
LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name' [REPLACE | IGNORE] INTO TABLEtbl_name[CHARACTER SETcharset_name] [{FIELDS | COLUMNS} [TERMINATED BY 'string'] [[OPTIONALLY] ENCLOSED BY 'char'] [ESCAPED BY 'char'] ] [LINES [STARTING BY 'string'] [TERMINATED BY 'string'] ] [IGNOREnumberLINES] [(col_name_or_user_var,...)] [SETcol_name=expr,...]
The LOAD DATA
INFILE statement reads rows from a text file into a
table at a very high speed. The file name must be given as a
literal string.
LOAD DATA
INFILE is the complement of
SELECT ... INTO
OUTFILE. (See Section 12.2.9, “SELECT Syntax”.) To write data
from a table to a file, use
SELECT ... INTO
OUTFILE. To read the file back into a table, use
LOAD DATA
INFILE. The syntax of the FIELDS and
LINES clauses is the same for both statements.
Both clauses are optional, but FIELDS must
precede LINES if both are specified.
For more information about the efficiency of
INSERT versus
LOAD DATA
INFILE and speeding up
LOAD DATA
INFILE, see Section 7.2.25, “Speed of INSERT Statements”.
The character set indicated by the
character_set_database system
variable is used to interpret the information in the file.
SET NAMES and the setting of
character_set_client do not
affect interpretation of input. If the contents of the input file
use a character set that differs from the default, it is usually
preferable to specify the character set of the file by using the
CHARACTER SET clause.
LOAD DATA
INFILE interprets all fields in the file as having the
same character set, regardless of the data types of the columns
into which field values are loaded. For proper interpretation of
file contents, you must ensure that it was written with the
correct character set. For example, if you write a data file with
mysqldump -T or by issuing a
SELECT ... INTO
OUTFILE statement in mysql, be sure
to use a --default-character-set option with
mysqldump or mysql so that
output is written in the character set to be used when the file is
loaded with LOAD DATA
INFILE.
Note that it is currently not possible to load data files that use
the ucs2, utf16, or
utf32 character set.
The character_set_filesystem
system variable controls the interpretation of the file name.
You can also load data files by using the
mysqlimport utility; it operates by sending a
LOAD DATA
INFILE statement to the server. The
--local option causes
mysqlimport to read data files from the client
host. You can specify the
--compress option to get
better performance over slow networks if the client and server
support the compressed protocol. See
Section 4.5.5, “mysqlimport — A Data Import Program”.
If you use LOW_PRIORITY, execution of the
LOAD DATA statement is delayed
until no other clients are reading from the table. This affects
only storage engines that use only table-level locking
(MyISAM, MEMORY,
MERGE).
If you specify CONCURRENT with a
MyISAM table that satisfies the condition for
concurrent inserts (that is, it contains no free blocks in the
middle), other threads can retrieve data from the table while
LOAD DATA is executing. Using this
option affects the performance of LOAD
DATA a bit, even if no other thread is using the table
at the same time.
CONCURRENT is not replicated when using
statement-based replication; however, it is replicated when using
row-based replication. See
Section 16.3.1.12, “Replication and LOAD DATA”, for more
information.
Note
Prior to MySQL 6.0.4, LOAD DATA
performed very poorly when importing into partitioned tables.
The statement now uses buffering to improve performance;
however, the buffer uses 130 KB memory per partition to achieve
this. (Bug#26527)
The LOCAL keyword, if specified, is interpreted
with respect to the client end of the connection:
If
LOCALis specified, the file is read by the client program on the client host and sent to the server. The file can be given as a full path name to specify its exact location. If given as a relative path name, the name is interpreted relative to the directory in which the client program was started.If
LOCALis not specified, the file must be located on the server host and is read directly by the server. The server uses the following rules to locate the file:If the file name is an absolute path name, the server uses it as given.
If the file name is a relative path name with one or more leading components, the server searches for the file relative to the server's data directory.
If a file name with no leading components is given, the server looks for the file in the database directory of the default database.
Note that, in the non-LOCAL case, these rules
mean that a file named as ./myfile.txt is
read from the server's data directory, whereas the file named as
myfile.txt is read from the database
directory of the default database. For example, if
db1 is the default database, the following
LOAD DATA statement reads the file
data.txt from the database directory for
db1, even though the statement explicitly loads
the file into a table in the db2 database:
LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;
Windows path names are specified using forward slashes rather than backslashes. If you do use backslashes, you must double them.
For security reasons, when reading text files located on the
server, the files must either reside in the database directory or
be readable by all. Also, to use
LOAD DATA
INFILE on server files, you must have the
FILE privilege. See
Section 5.4.1, “Privileges Provided by MySQL”. For
non-LOCAL load operations, if the
secure_file_priv system variable
is set to a nonempty directory name, the file to be loaded must be
located in that directory.
Using LOCAL is a bit slower than letting the
server access the files directly, because the contents of the file
must be sent over the connection by the client to the server. On
the other hand, you do not need the
FILE privilege to load local files.
With LOCAL, the default behavior is the same as
if IGNORE is specified; this is because the
server has no way to stop transmission of the file in the middle
of the operation. IGNORE is explained further
later in this section.
LOCAL works only if your server and your client
both have been enabled to allow it. For example, if
mysqld was started with
--local-infile=0,
LOCAL does not work. See
Section 5.3.4, “Security Issues with LOAD
DATA LOCAL”.
On Unix, if you need LOAD DATA to
read from a pipe, you can use the following technique (here we
load the listing of the / directory into a
table):
mkfifo /mysql/db/x/x chmod 666 /mysql/db/x/x find / -ls > /mysql/db/x/x & mysql -e "LOAD DATA INFILE 'x' INTO TABLE x" x
Note that you must run the command that generates the data to be loaded and the mysql commands either on separate terminals, or run the data generation process in the background (as shown in the preceding example). If you do not do this, the pipe will block until data is read by the mysql process.
The REPLACE and
IGNORE keywords control handling of input rows
that duplicate existing rows on unique key values:
If you specify
REPLACE, input rows replace existing rows. In other words, rows that have the same value for a primary key or unique index as an existing row. See Section 12.2.8, “REPLACESyntax”.If you specify
IGNORE, input rows that duplicate an existing row on a unique key value are skipped. If you do not specify either option, the behavior depends on whether theLOCALkeyword is specified. WithoutLOCAL, an error occurs when a duplicate key value is found, and the rest of the text file is ignored. WithLOCAL, the default behavior is the same as ifIGNOREis specified; this is because the server has no way to stop transmission of the file in the middle of the operation.
If you want to ignore foreign key constraints during the load
operation, you can issue a SET foreign_key_checks =
0 statement before executing LOAD
DATA.
If you use LOAD DATA
INFILE on an empty MyISAM table, all
nonunique indexes are created in a separate batch (as for
REPAIR TABLE). Normally, this makes
LOAD DATA
INFILE much faster when you have many indexes. In some
extreme cases, you can create the indexes even faster by turning
them off with ALTER TABLE ... DISABLE KEYS
before loading the file into the table and using ALTER
TABLE ... ENABLE KEYS to re-create the indexes after
loading the file. See Section 7.2.25, “Speed of INSERT Statements”.
For both the LOAD DATA
INFILE and
SELECT ... INTO
OUTFILE statements, the syntax of the
FIELDS and LINES clauses is
the same. Both clauses are optional, but FIELDS
must precede LINES if both are specified.
If you specify a FIELDS clause, each of its
subclauses (TERMINATED BY,
[OPTIONALLY] ENCLOSED BY, and ESCAPED
BY) is also optional, except that you must specify at
least one of them.
If you specify no FIELDS clause, the defaults
are the same as if you had written this:
FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
If you specify no LINES clause, the defaults
are the same as if you had written this:
LINES TERMINATED BY '\n' STARTING BY ''
In other words, the defaults cause
LOAD DATA
INFILE to act as follows when reading input:
Look for line boundaries at newlines.
Do not skip over any line prefix.
Break lines into fields at tabs.
Do not expect fields to be enclosed within any quoting characters.
Interpret occurrences of tab, newline, or “
\” preceded by “\” as literal characters that are part of field values.
Conversely, the defaults cause
SELECT ... INTO
OUTFILE to act as follows when writing output:
Write tabs between fields.
Do not enclose fields within any quoting characters.
Use “
\” to escape instances of tab, newline, or “\” that occur within field values.Write newlines at the ends of lines.
Backslash is the MySQL escape character within strings, so to
write FIELDS ESCAPED BY '\\', you must specify
two backslashes for the value to be interpreted as a single
backslash.
Note
If you have generated the text file on a Windows system, you
might have to use LINES TERMINATED BY '\r\n'
to read the file properly, because Windows programs typically
use two characters as a line terminator. Some programs, such as
WordPad, might use \r as a
line terminator when writing files. To read such files, use
LINES TERMINATED BY '\r'.
If all the lines you want to read in have a common prefix that you
want to ignore, you can use LINES STARTING BY
' to skip over
the prefix, and anything before it. If a line
does not include the prefix, the entire line is skipped. Suppose
that you issue the following statement:
prefix_string'
LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test FIELDS TERMINATED BY ',' LINES STARTING BY 'xxx';
If the data file looks like this:
xxx"abc",1 something xxx"def",2 "ghi",3
The resulting rows will be ("abc",1) and
("def",2). The third row in the file is skipped
because it does not contain the prefix.
The IGNORE option can be used to ignore lines at the start of
the file. For example, you can use number
LINESIGNORE 1
LINES to skip over an initial header line containing
column names:
LOAD DATA INFILE '/tmp/test.txt' INTO TABLE test IGNORE 1 LINES;
When you use SELECT ...
INTO OUTFILE in tandem with
LOAD DATA
INFILE to write data from a database into a file and
then read the file back into the database later, the field- and
line-handling options for both statements must match. Otherwise,
LOAD DATA
INFILE will not interpret the contents of the file
properly. Suppose that you use
SELECT ... INTO
OUTFILE to write a file with fields delimited by commas:
SELECT * INTO OUTFILE 'data.txt' FIELDS TERMINATED BY ',' FROM table2;
To read the comma-delimited file back in, the correct statement would be:
LOAD DATA INFILE 'data.txt' INTO TABLE table2 FIELDS TERMINATED BY ',';
If instead you tried to read in the file with the statement shown
following, it wouldn't work because it instructs
LOAD DATA
INFILE to look for tabs between fields:
LOAD DATA INFILE 'data.txt' INTO TABLE table2 FIELDS TERMINATED BY '\t';
The likely result is that each input line would be interpreted as a single field.
LOAD DATA
INFILE can be used to read files obtained from external
sources. For example, many programs can export data in
comma-separated values (CSV) format, such that lines have fields
separated by commas and enclosed within double quotes. If lines in
such a file are terminated by newlines, the statement shown here
illustrates the field- and line-handling options you would use to
load the file:
LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n';
If the input values are not necessarily enclosed within quotes,
use OPTIONALLY before the ENCLOSED
BY keywords.
Any of the field- or line-handling options can specify an empty
string (''). If not empty, the FIELDS
[OPTIONALLY] ENCLOSED BY and FIELDS ESCAPED
BY values must be a single character. The
FIELDS TERMINATED BY, LINES STARTING
BY, and LINES TERMINATED BY values
can be more than one character. For example, to write lines that
are terminated by carriage return/linefeed pairs, or to read a
file containing such lines, specify a LINES TERMINATED BY
'\r\n' clause.
To read a file containing jokes that are separated by lines
consisting of %%, you can do this
CREATE TABLE jokes (a INT NOT NULL AUTO_INCREMENT PRIMARY KEY, joke TEXT NOT NULL); LOAD DATA INFILE '/tmp/jokes.txt' INTO TABLE jokes FIELDS TERMINATED BY '' LINES TERMINATED BY '\n%%\n' (joke);
FIELDS [OPTIONALLY] ENCLOSED BY controls
quoting of fields. For output
(SELECT ... INTO
OUTFILE), if you omit the word
OPTIONALLY, all fields are enclosed by the
ENCLOSED BY character. An example of such
output (using a comma as the field delimiter) is shown here:
"1","a string","100.20" "2","a string containing a , comma","102.20" "3","a string containing a \" quote","102.20" "4","a string containing a \", quote and comma","102.20"
If you specify OPTIONALLY, the
ENCLOSED BY character is used only to enclose
values from columns that have a string data type (such as
CHAR,
BINARY,
TEXT, or
ENUM):
1,"a string",100.20 2,"a string containing a , comma",102.20 3,"a string containing a \" quote",102.20 4,"a string containing a \", quote and comma",102.20
Note that occurrences of the ENCLOSED BY
character within a field value are escaped by prefixing them with
the ESCAPED BY character. Also note that if you
specify an empty ESCAPED BY value, it is
possible to inadvertently generate output that cannot be read
properly by LOAD DATA
INFILE. For example, the preceding output just shown
would appear as follows if the escape character is empty. Observe
that the second field in the fourth line contains a comma
following the quote, which (erroneously) appears to terminate the
field:
1,"a string",100.20 2,"a string containing a , comma",102.20 3,"a string containing a " quote",102.20 4,"a string containing a ", quote and comma",102.20
For input, the ENCLOSED BY character, if
present, is stripped from the ends of field values. (This is true
regardless of whether OPTIONALLY is specified;
OPTIONALLY has no effect on input
interpretation.) Occurrences of the ENCLOSED BY
character preceded by the ESCAPED BY character
are interpreted as part of the current field value.
If the field begins with the ENCLOSED BY
character, instances of that character are recognized as
terminating a field value only if followed by the field or line
TERMINATED BY sequence. To avoid ambiguity,
occurrences of the <