ALTER [IGNORE] TABLEtbl_namealter_specification[,alter_specification] ... [partition_options] ALTER [IGNORE] TABLEtbl_namepartition_optionsalter_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 | ADD PARTITION (partition_definition) | DROP PARTITIONpartition_names| TRUNCATE PARTITION {partition_names| ALL } | COALESCE PARTITIONnumber| REORGANIZE PARTITIONpartition_namesINTO (partition_definitions) | ANALYZE PARTITION {partition_names| ALL } | CHECK PARTITION {partition_names| ALL } | OPTIMIZE PARTITION {partition_names| ALL } | REBUILD PARTITION {partition_names| ALL } | REPAIR PARTITION {partition_names| ALL } | REMOVE PARTITIONINGindex_col_name:col_name[(length)] [ASC | DESC]index_type: USING {BTREE | HASH}index_option: KEY_BLOCK_SIZE [=]value|index_type| WITH PARSERparser_name| COMMENT 'string'table_options:table_option[[,]table_option] ... (seeCREATE TABLEoptions)partition_options: (seeCREATE TABLEoptions)
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 permissible 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.4.5.41, “SHOW WARNINGS Syntax”.
In most cases, ALTER TABLE makes a
temporary copy of the original table. MySQL incorporates the
alteration into the copy, then deletes the original table and
renames the new one. 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
differ from the database directory of the original table for
ALTER TABLE operations that rename
the table to a different database.
For some operations, a “fast”
ALTER TABLE is possible that does
not require a temporary table:
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:Renaming a column.
Changing the default value of a column.
Changing the definition of an
ENUMorSETcolumn by adding new enumeration or set members to the end of the list of valid member values. (Adding members in the middle of the list causes renumbering of existing members, which requires a table copy.)
For
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.
In 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.
You can force an ALTER TABLE operation that
would otherwise require a table copy to use the temporary table
method (as supported in MySQL 5.0) by setting
old-alter-table to ON.
For information on troubleshooting ALTER
TABLE, see Section C.5.7.1, “Problems with ALTER TABLE”.
To use
ALTER TABLE, you needALTER,INSERT, andCREATEprivileges for the table.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.7, “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 permits 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 that 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.WarningThis 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.7, “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 permit 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 preferred position is after the column list. Use of the option before the column list will no longer be recognized in a future MySQL release.index_optionvalues specify additional options for an index.USINGis one such option. For details about permissibleindex_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.4.5.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 permits 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 permitted as sort criteria; arbitrary expressions are not permitted.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.NoteWhen 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.6.5.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.8.5, “MySQL Differences from Standard SQL”.ImportantThe 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.NotePartitioned tables do not support foreign keys. See Section 18.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.6.5.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;The tablespace file must have been created on the server into which it is imported later.
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 three bytes, for a maximum possible length of 3 × 65,535 = 196,605 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 196,605. 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.WarningThe
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 18.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.Beginning with MySQL 5.5.0, it is possible to delete rows from selected partitions using the
TRUNCATE PARTITIONoption. This option takes a comma-separated list of one or more partition names. For example, consider the tablet1as defined 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), PARTITION p3 VALUES LESS THAN (2003), PARTITION p4 VALUES LESS THAN (2007) );To delete all rows from partition
p0, you can use the following statement:ALTER TABLE t1 TRUNCATE PARTITION p0;
The statement just shown has the same effect as the following
DELETEstatement:DELETE FROM t1 WHERE year_col < 1991;
When truncating multiple partitions, the partitions do not have to be contiguous: This can greatly simplify delete operations on partitioned tables that would otherwise require very complex
WHEREconditions if done withDELETEstatements. For example, this statement deletes all rows from partitionsp1andp3:ALTER TABLE t1 TRUNCATE PARTITION p1, p3;
An equivalent
DELETEstatement is shown here:DELETE FROM t1 WHERE (year_col >= 1991 AND year_col < 1995) OR (year_col >= 2003 AND year_col < 2007);You can also use the
ALLkeyword in place of the list of partition names; in this case, the statement acts on all partitions in the table.TRUNCATE PARTITIONmerely deletes rows; it does not alter the definition of the table itself, or of any of its partitions.NoteTRUNCATE PARTITIONdoes not work with subpartitions.You can verify that the rows were dropped by checking the
INFORMATION_SCHEMA.PARTITIONStable, using a query such as this one:SELECT PARTITION_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME = 't1';TRUNCATE PARTITIONis supported only for partitioned tables that use theMyISAM,InnoDB, orMEMORYstorage engine. It also works onBLACKHOLEtables (but has no effect). It is not supported forARCHIVEtables.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.
NoteFor 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 18.3.1, “Management ofRANGEandLISTPartitions”.Several additional options provide 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; see Section 12.4.2, “Table Maintenance Statements” for more information). 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. You can also use theALLkeyword in place ofpartition_names, in which case the statement acts on all partitions in the table. For more information and examples, see Section 18.3.3, “Maintenance of Partitions”.The
ANALYZE PARTITION,CHECK PARTITION,OPTIMIZE PARTITION, andREPAIR PARTITIONoptions are not permitted for tables which are not partitioned.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.
Only a single instance of any
one of the following options can be used in
a given ALTER TABLE statement:
PARTITION BY, ADD
PARTITION, DROP PARTITION,
TRUNCATE PARTITION, REORGANIZE
PARTITION, or COALESCE PARTITION,
ANALYZE PARTITION, CHECK
PARTITION, OPTIMIZE PARTITION,
REBUILD PARTITION, REMOVE
PARTITIONING.
For example, the following two statements are invalid:
ALTER TABLE t1 ANALYZE PARTITION p1, ANALYZE PARTITION p2; ALTER TABLE t1 ANALYZE PARTITION p1, CHECK PARTITION p2;
In the first case, you can analyze partitions
p1 and p2 of table
t1 concurrently using a single statement with
a single ANALYZE PARTITION option that lists
both of the partitions to be analyzed, like this:
ALTER TABLE t1 ANALYZE PARTITION p1, p2;
In the second case, it is not possible to perform
ANALYZE and CHECK
operations on different partitions of the same table
concurrently. Instead, you must issue two separate statements,
like this:
ALTER TABLE t1 ANALYZE PARTITION p1; ALTER TABLE t1 CHECK PARTITION p2;
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 22.9.3.35, “mysql_info()”.
ALTER TABLE Examples
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);
We indexed c (as a PRIMARY
KEY) because AUTO_INCREMENT columns
must be indexed, and 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.4, “Server 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;
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;