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_name
column_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
| CHECK (expr
)column_definition
:data_type
[NOT NULL | NULL] [DEFAULTdefault_value
] [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] [COMMENT 'string
'] [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}] [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_type
index_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
'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} | UNION [=] (tbl_name
[,tbl_name
]...)partition_options
: PARTITION BY { [LINEAR] HASH(expr
) | [LINEAR] KEY(column_list
) | RANGE{(expr
) | COLUMNS(column_list
)} | LIST{(expr
) | COLUMNS(column_list
)} } [PARTITIONSnum
] [SUBPARTITION BY { [LINEAR] HASH(expr
) | [LINEAR] KEY(column_list
) } [SUBPARTITIONSnum
] ] [(partition_definition
[,partition_definition
] ...)]partition_definition
: PARTITIONpartition_name
[VALUES {LESS THAN {(expr
|value_list
) |MAXVALUE
} | IN (value_list
)}] [[STORAGE] ENGINE [=]engine_name
] [COMMENT [=]'comment_text'
] [DATA DIRECTORY [=] ''] [INDEX DIRECTORY [=] '
data_dir
'] [MAX_ROWS [=]
index_dir
max_number_of_rows
] [MIN_ROWS [=]min_number_of_rows
] [(subpartition_definition
[,subpartition_definition
] ...)]subpartition_definition
: SUBPARTITIONlogical_name
[[STORAGE] ENGINE [=]engine_name
] [COMMENT [=]'comment_text'
] [DATA DIRECTORY [=] ''] [INDEX DIRECTORY [=] '
data_dir
'] [MAX_ROWS [=]
index_dir
max_number_of_rows
] [MIN_ROWS [=]min_number_of_rows
]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 permissible 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.
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.17, “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
NULL
norNOT NULL
is specified, the column is treated as thoughNULL
had been specified.An integer or floating-point column can have the additional attribute
AUTO_INCREMENT
. When you insert a value ofNULL
(recommended) or0
into an indexedAUTO_INCREMENT
column, the column is set to the next sequence value. Typically this is
, wherevalue
+1value
is the largest value for the column currently in the table.AUTO_INCREMENT
sequences begin with1
.To retrieve an
AUTO_INCREMENT
value after inserting a row, use theLAST_INSERT_ID()
SQL function or themysql_insert_id()
C API function. See Section 11.14, “Information Functions”, and Section 22.9.3.37, “mysql_insert_id()
”.If the
NO_AUTO_VALUE_ON_ZERO
SQL mode is enabled, you can store0
inAUTO_INCREMENT
columns as0
without generating a new sequence value. See Section 5.1.7, “Server SQL Modes”.NoteThere can be only one
AUTO_INCREMENT
column per table, it must be indexed, and it cannot have aDEFAULT
value. AnAUTO_INCREMENT
column 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_INCREMENT
column that contains0
.For
MyISAM
tables, you can specify anAUTO_INCREMENT
secondary 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_INCREMENT
value for the last inserted row with the following query:SELECT * FROM
tbl_name
WHEREauto_col
IS NULLFor information about
InnoDB
andAUTO_INCREMENT
, see Section 13.6.5.3, “AUTO_INCREMENT
Handling inInnoDB
”. For information aboutAUTO_INCREMENT
and MySQL Replication, see Section 17.4.1.1, “Replication andAUTO_INCREMENT
”.Character data types (
CHAR
,VARCHAR
,TEXT
) can includeCHARACTER SET
andCOLLATE
attributes to specify the character set and collation for the column. For details, see Section 9.1, “Character Set Support”.CHARSET
is a synonym forCHARACTER SET
. Example:CREATE TABLE t (c CHAR(20) CHARACTER SET utf8 COLLATE utf8_bin);
MySQL 5.5 interprets length specifications in character column definitions in characters. (Versions before MySQL 4.1 interpreted them in bytes.) Lengths for
BINARY
andVARBINARY
are in bytes.The
DEFAULT
clause 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_TIMESTAMP
as the default for aTIMESTAMP
column. See Section 10.3.1.1, “TIMESTAMP
Properties”.If a column definition includes no explicit
DEFAULT
value, MySQL determines the default value as described in Section 10.1.4, “Data Type Default Values”.BLOB
andTEXT
columns cannot be assigned a default value.CREATE TABLE
fails if a date-valued default is not correct according to theNO_ZERO_IN_DATE
SQL mode, even if strict SQL mode is not enabled. For example,c1 DATE DEFAULT '2010-00-00'
causesCREATE TABLE
to fail withInvalid default value for 'c1'
.A comment for a column can be specified with the
COMMENT
option, up to 1024 characters long (255 characters before MySQL 5.5.3). The comment is displayed by theSHOW CREATE TABLE
andSHOW FULL COLUMNS
statements.KEY
is normally a synonym forINDEX
. The key attributePRIMARY KEY
can also be specified as justKEY
when given in a column definition. This was implemented for compatibility with other database systems.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, aUNIQUE
index permits multipleNULL
values for columns that can containNULL
.A
PRIMARY KEY
is 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 KEY
and an application asks for thePRIMARY KEY
in your tables, MySQL returns the firstUNIQUE
index that has noNULL
columns as thePRIMARY KEY
.In
InnoDB
tables, having a longPRIMARY KEY
wastes a lot of space. (See Section 13.6.11, “InnoDB
Table and Index Structures”.)In the created table, a
PRIMARY KEY
is placed first, followed by allUNIQUE
indexes, and then the nonunique indexes. This helps the MySQL optimizer to prioritize which index to use and also more quickly to detect duplicatedUNIQUE
keys.A
PRIMARY KEY
can be a multiple-column index. However, you cannot create a multiple-column index using thePRIMARY KEY
key 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 KEY
orUNIQUE
index consists of only one column that has an integer type, you can also refer to the column as_rowid
inSELECT
statements.In MySQL, the name of a
PRIMARY KEY
isPRIMARY
. 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.4.5.23, “tbl_name
SHOW INDEX
Syntax”.Some storage engines permit you to specify an index type when creating an index. The syntax for the
index_type
specifier isUSING
.type_name
Example:
CREATE TABLE lookup (id INT, INDEX USING BTREE (id)) ENGINE = MEMORY;
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_option
values specify additional options for an index.USING
is one such option. For details about permissibleindex_option
values, see Section 12.1.11, “CREATE INDEX
Syntax”.For more information about indexes, see Section 7.3.1, “How MySQL Uses Indexes”.
In MySQL 5.5, only the
MyISAM
,InnoDB
, andMEMORY
storage engines support indexes on columns that can haveNULL
values. In other cases, you must declare indexed columns asNOT NULL
or an error results.For
CHAR
,VARCHAR
,BINARY
, andVARBINARY
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
)BLOB
andTEXT
columns 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 firstlength
characters of each column value forCHAR
,VARCHAR
, andTEXT
columns, and the firstlength
bytes of each column value forBINARY
,VARBINARY
, andBLOB
columns. Indexing only a prefix of column values like this can make the index file much smaller. See Section 7.3.4, “Column Indexes”.Only the
MyISAM
andInnoDB
storage engines support indexing onBLOB
andTEXT
columns. For example:CREATE TABLE test (blob_col BLOB, INDEX(blob_col(10)));
Prefixes can be up to 1000 bytes long (767 bytes for
InnoDB
tables). Note that prefix limits are measured in bytes, whereas the prefix length inCREATE TABLE
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.An
index_col_name
specification can end withASC
orDESC
. These keywords are permitted 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 BY
orGROUP BY
on aTEXT
orBLOB
column in aSELECT
, the server sorts values using only the initial number of bytes indicated by themax_sort_length
system variable. See Section 10.4.3, “TheBLOB
andTEXT
Types”.You can create special
FULLTEXT
indexes, which are used for full-text searches. Only theMyISAM
storage engine supportsFULLTEXT
indexes. They can be created only fromCHAR
,VARCHAR
, andTEXT
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.9, “Full-Text Search Functions”, for details of operation. AWITH PARSER
clause can be specified as anindex_option
value to associate a parser plugin with the index if full-text indexing and searching operations need special handling. This clause is legal only forFULLTEXT
indexes. See Section 23.2, “The MySQL Plugin API”, for details on creating plugins.You can create
SPATIAL
indexes on spatial data types. Spatial types are supported only forMyISAM
tables and indexed columns must be declared asNOT NULL
. See Section 11.17, “Spatial Extensions”.As of MySQL 5.5.3, index definitions can include an optional comment of up to 1024 characters.
InnoDB
tables support checking of foreign key constraints. See Section 13.6, “TheInnoDB
Storage Engine”. Note that theFOREIGN KEY
syntax inInnoDB
is more restrictive than the syntax presented for theCREATE TABLE
statement at the beginning of this section: The columns of the referenced table must always be explicitly named.InnoDB
supports bothON DELETE
andON UPDATE
actions on foreign keys. For the precise syntax, see Section 13.6.5.4, “FOREIGN KEY
Constraints”.For other storage engines, MySQL Server parses and ignores the
FOREIGN KEY
andREFERENCES
syntax inCREATE TABLE
statements. TheCHECK
clause is parsed but ignored by all storage engines. See Section 1.8.5.4, “Foreign Key Differences”.ImportantFor users familiar with the ANSI/ISO SQL Standard, please note that no storage engine, including
InnoDB
, recognizes or enforces theMATCH
clause used in referential integrity constraint definitions. Use of an explicitMATCH
clause will not have the specified effect, and also causesON DELETE
andON UPDATE
clauses to be ignored. For these reasons, specifyingMATCH
should be avoided.The
MATCH
clause in the SQL standard controls howNULL
values in a composite (multiple-column) foreign key are handled when comparing to a primary key.InnoDB
essentially implements the semantics defined byMATCH SIMPLE
, which permit a foreign key to be all or partiallyNULL
. In that case, the (child table) row containing such a foreign key is permitted 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
InnoDB
require that the referenced columns be indexed for performance. However, the system does not enforce a requirement that the referenced columns beUNIQUE
or be declaredNOT NULL
. The handling of foreign key references to nonunique keys or keys that containNULL
values is not well defined for operations such asUPDATE
orDELETE CASCADE
. You are advised to use foreign keys that reference onlyUNIQUE
andNOT NULL
keys.Furthermore,
InnoDB
does not recognize or support “inlineREFERENCES
specifications” (as defined in the SQL standard) where the references are defined as part of the column specification.InnoDB
acceptsREFERENCES
clauses only when specified as part of a separateFOREIGN KEY
specification. For other storage engines, MySQL Server parses and ignores foreign key specifications.NotePartitioned tables do not support foreign keys. See Section 18.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 E.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.12, “The ARCHIVE Storage Engine”. |
CSV | Tables that store rows in comma-separated values format. See
Section 13.13, “The CSV Storage Engine”. |
EXAMPLE | An example engine. See Section 13.10, “The EXAMPLE Storage Engine”. |
FEDERATED | Storage engine that accesses remote tables. See
Section 13.11, “The FEDERATED Storage Engine”. |
HEAP | This is a synonym for MEMORY . |
ISAM (OBSOLETE) | Not available in MySQL 5.5. If you are upgrading to MySQL
5.5 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.6, “The InnoDB Storage Engine”. |
MEMORY | The data for this storage engine is stored only in memory. See
Section 13.9, “The MEMORY Storage Engine”. |
MERGE | A collection of MyISAM tables used as one table. Also
known as MRG_MyISAM . See
Section 13.8, “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
5.5, 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.7, “Server SQL Modes”.
The older TYPE
option was synonymous with
ENGINE
. TYPE
was
deprecated in MySQL 4.0 and removed in MySQL 5.5. When
upgrading to MySQL 5.5 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_INCREMENT
The initial
AUTO_INCREMENT
value for the table. In MySQL 5.5, this works forMyISAM
,MEMORY
,InnoDB
, andARCHIVE
tables. To set the first auto-increment value for engines that do not support theAUTO_INCREMENT
table 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_INCREMENT
table option inCREATE TABLE
statements, you can also useALTER TABLE
to reset thetbl_name
AUTO_INCREMENT =N
AUTO_INCREMENT
value. The value cannot be set lower than the maximum value currently in the column.AVG_ROW_LENGTH
An 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
MyISAM
table, MySQL uses the product of theMAX_ROWS
andAVG_ROW_LENGTH
options to decide how big the resulting table is. If you don't specify either option, the maximum size forMyISAM
data 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_size
system 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 permits table sizes up to 65,536TB.[DEFAULT] CHARACTER SET
Specify a default character set for the table.
CHARSET
is a synonym forCHARACTER SET
. If the character set name isDEFAULT
, the database character set is used.CHECKSUM
Set 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 TABLE
statement reports the checksum. (MyISAM
only.)[DEFAULT] COLLATE
Specify a default collation for the table.
COMMENT
A comment for the table, up to 2048 characters long (60 characters before MySQL 5.5.3).
CONNECTION
The connection string for a
FEDERATED
table.NoteOlder versions of MySQL used a
COMMENT
option for the connection string.DATA DIRECTORY
,INDEX DIRECTORY
By using
DATA DIRECTORY='
ordirectory
'INDEX DIRECTORY='
you can specify where thedirectory
'MyISAM
storage 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.ImportantTable-level
DATA DIRECTORY
andINDEX DIRECTORY
options are ignored for partitioned tables. (Bug#32091)These options work only when you are not using the
--skip-symbolic-links
option. Your operating system must also have a working, thread-saferealpath()
call. See Section 7.11.3.1.2, “Using Symbolic Links for Tables on Unix”, for more complete information.If a
MyISAM
table is created with noDATA DIRECTORY
option, the.MYD
file is created in the database directory. By default, ifMyISAM
finds an existing.MYD
file in this case, it overwrites it. The same applies to.MYI
files for tables created with noINDEX DIRECTORY
option. To suppress this behavior, start the server with the--keep_files_on_create
option, in which caseMyISAM
will not overwrite existing files and returns an error instead.If a
MyISAM
table is created with aDATA DIRECTORY
orINDEX DIRECTORY
option and an existing.MYD
or.MYI
file is found, MyISAM always returns an error. It will not overwrite a file in the specified directory.ImportantYou cannot use path names that contain the MySQL data directory with
DATA DIRECTORY
orINDEX DIRECTORY
. This includes partitioned tables and individual table partitions. (See Bug#32167.)DELAY_KEY_WRITE
Set 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_write
system variable in Section 5.1.4, “Server System Variables”. (MyISAM
only.)INSERT_METHOD
If you want to insert data into a
MERGE
table, you must specify withINSERT_METHOD
the table into which the row should be inserted.INSERT_METHOD
is an option useful forMERGE
tables only. Use a value ofFIRST
orLAST
to have inserts go to the first or last table, or a value ofNO
to prevent inserts. See Section 13.8, “TheMERGE
Storage Engine”.KEY_BLOCK_SIZE
This option provides a hint to the storage engine about the size in bytes to use for index key blocks. The engine is permitted 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_SIZE
value of their own to override the table value.MAX_ROWS
The 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.
The maximum
MAX_ROWS
value is 4294967295; larger values are truncated to this limit.MIN_ROWS
The minimum number of rows you plan to store in the table. The
MEMORY
storage engine uses this option as a hint about memory use.PACK_KEYS
PACK_KEYS
takes effect only withMyISAM
tables. 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 toDEFAULT
tells the storage engine to pack only longCHAR
,VARCHAR
,BINARY
, orVARBINARY
columns.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 haveNULL
values. (In this case, the packed key length is stored in the same byte that is used to mark if a key isNULL
.)PASSWORD
This option is unused. If you have a need to scramble your
.frm
files and make them unusable to any other MySQL server, please contact our sales department.RAID_TYPE
RAID
support has been removed as of MySQL 5.0.ROW_FORMAT
Defines how the rows should be stored. For
MyISAM
tables, the option value can beFIXED
orDYNAMIC
for static or variable-length row format. myisampack sets the type toCOMPRESSED
. See Section 13.5.3, “MyISAM
Table Storage Formats”.For
InnoDB
tables, 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
.NoteWhen executing a
CREATE TABLE
statement, 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 STATUS
is the actual row format used. This may differ from the value in theCreate_options
column because the originalCREATE TABLE
definition is retained during creation.UNION
is used when you want to access a collection of identicalMyISAM
tables as one. This works only withMERGE
tables. See Section 13.8, “TheMERGE
Storage Engine”.You must have
SELECT
,UPDATE
, andDELETE
privileges for the tables you map to aMERGE
table.NoteFormerly, all tables used had to be in the same database as the
MERGE
table itself. This restriction no longer applies.
partition_options
can be used to
control partitioning of the table created with
CREATE TABLE
.
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 18, 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 5.5 are
shown in the following list:
HASH(
: Hashes one or more columns to create a key for placing and locating rows.expr
)expr
is 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 both validCREATE TABLE
statements usingPARTITION BY HASH
:CREATE TABLE t1 (col1 INT, col2 CHAR(5)) PARTITION BY HASH(col1); CREATE TABLE t1 (col1 INT, col2 CHAR(5), col3 DATETIME) PARTITION BY HASH ( YEAR(col3) );
You may not use either
VALUES LESS THAN
orVALUES IN
clauses withPARTITION BY HASH
.PARTITION BY HASH
uses the remainder ofexpr
divided by the number of partitions (that is, the modulus). For examples and additional information, see Section 18.2.4, “HASH
Partitioning”.The
LINEAR
keyword 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 logicalAND
operations. For discussion and examples of linear hashing, see Section 18.2.4.1, “LINEAR HASH
Partitioning”.KEY(
: This is similar tocolumn_list
)HASH
, except that MySQL supplies the hashing function so as to guarantee an even data distribution. Thecolumn_list
argument 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
LINEAR
keyword. 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 18.2.4.1, “LINEAR HASH
Partitioning”, and Section 18.2.5, “KEY
Partitioning”, 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 THAN
orVALUES IN
clauses withPARTITION BY KEY
.RANGE
: In this case,expr
shows a range of values using a set ofVALUES LESS THAN
operators. When using range partitioning, you must define at least one partition usingVALUES LESS THAN
. You cannot useVALUES IN
with range partitioning.When used with a table partitioned by
RANGE
,VALUES LESS THAN
must be used with either an integer literal value or an expression that evaluates to a single integer value. In MySQL 5.5, this limitation can be overcome in a table that is defined usingPARTITION BY RANGE COLUMNS
, as described later in this section.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 to 1994 2 1995 to 1998 3 1999 to 2002 4 2003 to 2005 5 2006 and later A table implementing such a partitioning scheme can be realized by the
CREATE TABLE
statement 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 MAXVALUE
works to specify “leftover” values that are greater than the maximum value otherwise specified.Note that
VALUES LESS THAN
clauses work sequentially in a manner similar to that of thecase
portions of aswitch ... case
block (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 THAN
is greater than that of the previous one, with the one referencingMAXVALUE
coming last of all in the list.RANGE COLUMNS(
: This variant oncolumn_list
)RANGE
was introduced in MySQL 5.5.0 to facilitate partition pruning for queries using range conditions on multiple columns (that is, having conditions such asWHERE a = 1 AND b < 10
orWHERE a = 1 AND b = 10 AND c < 10
). It enables you to specify value ranges in multiple columns by using a list of columns in theCOLUMNS
clause and a set of column values in eachPARTITION ... VALUES LESS THAN (
partition definition clause. (In the simplest case, this set consists of a single column.) The maximum number of columns that can be referenced in thevalue_list
)column_list
andvalue_list
is 16.The
column_list
used in theCOLUMNS
clause may contain only names of columns; each column in the list must be one of the following MySQL data types: the integer types; the string types; and time or date column types. Columns usingBLOB
,TEXT
,SET
,ENUM
,BIT
, or spatial data types are not permitted; columns that use floating-point number types are also not permitted. You also may not use functions or arithmetic expressions in theCOLUMNS
clause.The
VALUES LESS THAN
clause used in a partition definition must specify a literal value for each column that appears in theCOLUMNS()
clause; that is, the list of values used for eachVALUES LESS THAN
clause must contain the same number of values as there are columns listed in theCOLUMNS
clause. An attempt to use more or fewer values in aVALUES LESS THAN
clause than there are in theCOLUMNS
clause causes the statement to fail with the error Inconsistency in usage of column lists for partitioning.... You cannot useNULL
for any value appearing inVALUES LESS THAN
. It is possible to useMAXVALUE
more than once for a given column other than the first, as shonw in this example:CREATE TABLE rc ( a INT NOT NULL, b INT NOT NULL ) PARTITION BY RANGE COLUMNS(a,b) ( PARTITION p0 VALUES LESS THAN (10,5), PARTITION p1 VALUES LESS THAN (20,10), PARTITION p2 VALUES LESS THAN (MAXVALUE,15), PARTITION p3 VALUES LESS THAN (MAXVALUE,MAXVALUE) );
Each value used in a
VALUES LESS THAN
value list must match the type of the corresponding column exactly; no conversion is made. For example, you cannot use the string"1"
for a value that matches a column that uses an integer type (you must use the numeral1
instead), nor can you use the numeral1
for a value that matches a column that uses a string type (in such a case, you must use a quoted string:"1"
).For more information, see Section 18.2.1, “
RANGE
Partitioning”, and Section 18.4, “Partition Pruning”.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 IN
may be used to specify permissible values for each partition.VALUES IN
is 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 THAN
withPARTITION BY LIST
.NoteFor tables partitioned by
LIST
, the value list used withVALUES IN
must consist of integer values only. In MySQL 5.5, you can overcome this limitation using partitioning byLIST COLUMNS
, which is described later in this section.LIST COLUMNS(
: This variant oncolumn_list
)LIST
was introduced in MySQL 5.5.0 to facilitate partition pruning for queries using comparison conditions on multiple columns (that is, having conditions such asWHERE a = 5 AND b = 5
orWHERE a = 1 AND b = 10 AND c = 5
). It enables you to specify values in multiple columns by using a list of columns in theCOLUMNS
clause and a set of column values in eachPARTITION ... VALUES IN (
partition definition clause.value_list
)The rules governing regarding data types for the column list used in
LIST COLUMNS(
and the value list used in VALUES IN(column_list
)value_list
) are the as those for the column list used inRANGE COLUMNS(
and the value list used incolumn_list
)VALUES LESS THAN(
, respectively, except that in thevalue_list
)VALUES IN
clause,MAXVALUE
is not permitted, and you may useNULL
.There is one important difference between the list of values used for
VALUES IN
withPARTITION BY LIST COLUMNS
as opposed to when it is used withPARTITION BY LIST
. When used withPARTITION BY LIST COLUMNS
, each element in theVALUES IN
clause must be a set of column values; the number of values in each set must be the same as the number of columns used in the COLUMNS clause, and the data types of these values must match those of the columns (and occur in the same order). In the simplest case, the set consists of a single column. The maximum number of columns that can be used in thecolumn_list
and in the elements making up thevalue_list
is 16.The table defined by the following
CREATE TABLE
statement provides an example of a table usingLIST COLUMNS
partitioning:CREATE TABLE lc ( a INT NULL, b INT NULL ) PARTITION BY LIST COLUMNS(a,b) ( PARTITION p0 VALUES IN( (0,0), (NULL,NULL) ), PARTITION p1 VALUES IN( (0,1), (0,2), (0,3), (1,1), (1,2) ), PARTITION p2 VALUES IN( (1,0), (2,0), (2,1), (3,0), (3,1) ), PARTITION p3 VALUES IN( (1,3), (2,2), (2,3), (3,2), (3,3) ) );
The number of partitions may optionally be specified with a
PARTITIONS
clause, wherenum
num
is the number of partitions. If both this clause and anyPARTITION
clauses are used,num
must be equal to the total number of any partitions that are declared usingPARTITION
clauses.NoteWhether or not you use a
PARTITIONS
clause in creating a table that is partitioned byRANGE
orLIST
, you must still include at least onePARTITION VALUES
clause 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 BY
clause. Subpartitioning may be done byHASH
orKEY
. 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 byLIST
orRANGE
.)The number of subpartitions can be indicated using the
SUBPARTITIONS
keyword followed by an integer value.Rigorous checking of the value used in
PARTITIONS
orSUBPARTITIONS
clauses is applied and this value must adhere to the following rules:The value must be a positive, nonzero integer.
No leading zeros are permitted.
The value must be an integer literal, and cannot not be an expression. For example,
PARTITIONS 0.2E+01
is not permitted, even though0.2E+01
evaluates to2
. (Bug#15890)
The expression (expr
) used in a
PARTITION BY
clause cannot refer to any
columns not in the table being created; such references are
specifically not permitted and cause 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_name
A
VALUES
clause: For range partitioning, each partition must include aVALUES LESS THAN
clause; for list partitioning, you must specify aVALUES IN
clause 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 18, Partitioning, for syntax examples.An optional
COMMENT
clause may be used to specify a string that describes the partition. Example:COMMENT = 'Data for the years previous to 1999'
DATA DIRECTORY
andINDEX DIRECTORY
may be used to indicate the directory where, respectively, the data and indexes for this partition are to be stored. Both the
and thedata_dir
must be absolute system path names. Example:index_dir
CREATE 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 DIRECTORY
andINDEX DIRECTORY
behave in the same way as in theCREATE TABLE
statement'stable_option
clause as used forMyISAM
tables.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 DIRECTORY
andINDEX DIRECTORY
options are not supported for individual partitions or subpartitions. These options are ignored on Windows, except that a warning is generated. (Bug#30459)NoteThe
DATA DIRECTORY
andINDEX DIRECTORY
options are ignored for creating partitioned tables ifNO_DIR_IN_CREATE
is in effect. (Bug#24633)MAX_ROWS
andMIN_ROWS
may be used to specify, respectively, the maximum and minimum number of rows to be stored in the partition. The values formax_number_of_rows
andmin_number_of_rows
must 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 partitioning handler accepts a
[STORAGE] ENGINE
option for bothPARTITION
andSUBPARTITION
. 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 permitted 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_definition
clauses. Each of these consists at a minimum of theSUBPARTITION
, wherename
name
is an identifier for the subpartition. Except for the replacement of thePARTITION
keyword withSUBPARTITION
, the syntax for a subpartition definition is identical to that for a partition definition.Subpartitioning must be done by
HASH
orKEY
, and can be done only onRANGE
orLIST
partitions. See Section 18.2.6, “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 18.3, “Partition Management”.
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 enables 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_tbl
SELECT * FROMorig_tbl
;
For more information, see Section 12.1.14.1, “CREATE TABLE ...
SELECT
Syntax”.
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_tbl
LIKEorig_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.
Beginning with MySQL 5.5.3, you cannot execute CREATE
TABLE
or CREATE TABLE ... LIKE
while a LOCK TABLES
statement is
in effect.
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.
If the original table is a TEMPORARY
table,
CREATE TABLE ... LIKE
does not preserve
TEMPORARY
. To create a
TEMPORARY
destination table, use
CREATE TEMPORARY TABLE ... LIKE
.