Você está na página 1de 14

13.1.1.

ALTER DATABASE Syntax

ALTER {DATABASE | SCHEMA} [db_name]


alter_specification [alter_specification] ...

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 as of MySQL
5.0.2.
The CHARACTER SET clause changes the default database character set. The
COLLATE clause changes the default database collation. Chapter 10, Character
Set Support, discusses character set and collation names.
The database name can be omitted, in which case the statement applies to the
default database.
13.1.2. ALTER TABLE Syntax

ALTER [IGNORE] TABLE tbl_name


alter_specification [, alter_specification] ...

alter_specification:
ADD [COLUMN] column_definition [FIRST | AFTER col_name ]
| ADD [COLUMN] (column_definition,...)
13.1.3. CREATE DATABASE
DATABASE Syntax

CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name


[create_specification [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 as of MySQL 5.0.2.
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. Chapter 10, 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 9.2, “Database, Table, Index, Column, and
Alias 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 8.10, “mysqladmin — Client for Administering a MySQL Server”.
Previous / Next / Up / Table of Contents
13.1.4. CREATE INDEX Syntax

CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name


[index_type]
ON tbl_name (index_col_name,...)

index_col_name:
col_name [(length)] [ASC | DESC]

index_type:
USING {BTREE | HASH}
CREATE INDEX is mapped to an ALTER TABLE statement to create indexes.
See Section 13.1.2, “ALTER TABLE Syntax”. For more information about
indexes, see Section 7.4.5, “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 13.1.5, “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.
For CHAR, VARCHAR, BINARY, and VARBINARY columns, indexes can be
created that use only the leading part of column values, using col_name(length)
syntax to specify an index prefix length. BLOB and TEXT columns also can be
indexed, but a prefix length must be given. Prefix lengths are given in characters
for non-binary string types and in bytes for binary string types. That is, index
entries consist of the first length characters of each column value for CHAR,
VARCHAR, and TEXT columns, and the first length bytes of each column value
for BINARY, VARBINARY, and BLOB columns.
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 partial columns for indexes can make the index file much smaller, which
could save a lot of disk space and might also speed up INSERT operations.
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 in CREATE INDEX
statements is interpreted as number of characters for non-binary data types
(CHAR, VARCHAR, TEXT). Take this into account when specifying a prefix length
for a column that uses a multi-byte character set.
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. This constraint does not apply to NULL values except for the
BDB storage engine. For other engines, a UNIQUE index allows multiple NULL
values for columns that can contain NULL.
FULLTEXT indexes are supported only for MyISAM tables and can include only
CHAR, VARCHAR, and TEXT columns. Indexing always happens over the entire
column; partial indexing is not supported and any prefix length is ignored if
specified. See Section 12.7, “Full-Text Search Functions”, for details of
operation.
SPATIAL indexes are supported only for MyISAM tables and can include only
spatial columns that are defined as NOT NULL. Chapter 16, Spatial Extensions,
describes the spatial data types.
In MySQL 5.0:

• You can add an index on a column that can have NULL values only if you are
using the MyISAM, InnoDB, BDB, or MEMORY storage engine.
• You can add an index on a BLOB or TEXT column only if you are using the
MyISAM, BDB, or InnoDB storage engine.

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.
Some 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
MyISAM BTREE

InnoDB BTREE

MEMORY/HEAP HASH, BTREE

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);
TYPE type_name is recognized as a synonym for USING type_name. However,
USING is the preferred form.
Previous / Next / Up / Table of Contents
13.1.5. CREATE TABLE Syntax

13.1.5.1. Silent Column Specification Changes


CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_option ...]

Or:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_option ...]
select_statement
Or:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{ LIKE old_tbl_name | (LIKE old_tbl_name) }

create_definition:
column_definition
13.1.5.1. Silent Column Specification Changes

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.
Some silent column specification changes include modifications to attribute or
index specifications:

• TIMESTAMP display sizes are discarded.


• Columns that are part of a PRIMARY KEY are made NOT NULL even if not
declared that way.
• Trailing spaces are automatically deleted from ENUM and SET member
values when the table is created.
• MySQL maps certain data types used by other SQL database vendors to
MySQL types. See Section 11.7, “Using Data Types from Other Database
Engines”.
• If you include a USING clause 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.

Possible data type changes are given in the following list. These occur only up to
to the versions listed. After that, an error occurs if a column cannot be created
using the specified data type.

• Before MySQL 5.0.3, VARCHAR columns with a length less than four are
changed to CHAR.
• Before MySQL 5.0.3, if any column in a table has a variable length, the entire
row becomes variable-length as a result. Therefore, if a table contains any
variable-length columns (VARCHAR, TEXT, or BLOB), all CHAR columns
longer than three characters are changed to VARCHAR columns. This does
not affect how you use the columns in any way; in MySQL, VARCHAR is just
a different way to store characters. MySQL performs this conversion because
it saves space and makes table operations faster. See Chapter 14, Storage
Engines and Table Types.
• Before MySQL 5.0.3, a CHAR or VARCHAR column with a length
specification greater than 255 is converted to the smallest TEXT type that can
hold values of the given length. For example, VARCHAR(500) is converted to
TEXT, and VARCHAR(200000) is converted to MEDIUMTEXT. Similar
conversions occur for BINARY and VARBINARY, except that they are
converted to a BLOB type.

Note that these conversions result in a change in behavior with regard to


treatment of trailing spaces.

As of MySQL 5.0.3, a CHAR or BINARY column with a length specification


greater than 255 is not silently converted. Instead, an error occurs. From
MySQL 5.0.6 on, silent conversion of VARCHAR and VARBINARY columns
with a length specification greater than 65,535 does not occur if strict SQL
mode is enabled. Instead, an error occurs.

• Before MySQL 5.0.10, for a specification of DECIMAL(M,D), if M is not larger


than D, it is adjusted upward. For example, DECIMAL(10,10) becomes
DECIMAL(11,10). As of MySQL 5.0.10, DECIMAL(10,10) is created as
specified.

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 14.1.3.3, “Compressed Table Characteristics”.
Previous / Next / Up / Table of Contents
13.1.6. DROP DATABASE
DATABASE Syntax

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
as of MySQL 5.0.2.
Important When a database is dropped, user privileges on the database are not
Important:
automatically dropped. See Section 13.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 these extensions:

.BAK .DAT .HSH .MRG

.MYD .MYI .TRG .TRN

.db .frm .ibd .ndb

• All subdirectories with names that consist of two hex digits 00-ff. These are
subdirectories used for RAID tables. (These directories are not removed as of
MySQL 5.0, when support for RAID tables was removed. You should convert
any existing RAID tables and remove these directories manually before
upgrading to MySQL 5.0. See Section 2.4.16.2, “Upgrading from MySQL 4.1
to 5.0”.)
• The db.opt file, 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 8.10, “mysqladmin
— Client for Administering a MySQL Server”.
Previous / Next / Up / Table of Contents
13.1.7. DROP INDEX Syntax

DROP INDEX index_name ON tbl_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 13.1.2, “ALTER TABLE Syntax”.
Previous / Next / Up / Table of Contents
13.1.8. DROP TABLE Syntax

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 non-existing 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
Important:
automatically dropped. See Section 13.5.1.3, “GRANT Syntax”.
Use IF EXISTS to prevent an error from occurring for tables that do not exist. A
NOTE is generated for each non-existent table when using IF EXISTS. See
Section 13.5.4.27, “SHOW WARNINGS Syntax”.
RESTRICT and CASCADE are allowed to make porting easier. In MySQL 5.0,
they do nothing.
Note:
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 TEMPORARY tables.


• The statement does not end an ongoing transaction.
• No access rights are checked. (A TEMPORARY table is visible only to the
client 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.
Previous / Next / Up / Table of Contents
13.1.9. RENAME TABLE Syntax

RENAME TABLE tbl_name TO new_tbl_name


[, tbl_name2 TO new_tbl_name2] ...

This statement renames one or more tables.


The rename operation is done atomically, which means that no other thread 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 filesystem, you can use RENAME
TABLE to move a table from one database to another:
RENAME TABLE current_db.tbl_name TO other_db.tbl_name;

Beginning with MySQL 5.0.2, 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.
As of MySQL 5.0.14, RENAME TABLE also works for views, as long as you do
not try to rename a view into a different database.
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.

Você também pode gostar