Sie sind auf Seite 1von 39

RDBMS with MySQL Unit 3

Unit 3 Data Definition Language (DDL)

Structure
3.1 Introduction
Objectives
3.2 CREATE DATABASE
3.3 CREATE INDEX
3.4 CREATE TABLE
3.5 ALTER DATABASE
3.6 ALTER TABLE
3.7 DROP DATABASE
3.8 DROP INDEX
3.9 DROP TABLE
3.10 DESCRIBE
3.11 Summary
3.12 Terminal Questions
3.13 Answers

3.1 Introduction
The Data Definition Language (DDL) in any database server is used to
define the structures used to store the data. The Data Definition language
presented in this unit is used to create indexes and tables within the
specified database. The methods used to alter or modify the existing data
structures like tables or indexes are discussed with appropriate examples.
To view the structure or metadata information regarding the created
structures in the database, we use the Describe command whose syntax is
presented
Objectives
After studying this units, you should be able to:
 explain various Data Definition Language (DDL) Statements
 apply various CREATE syntaxes to create the appropriate structures
 apply various ALTER syntaxes to modify the appropriate structures
 explain and apply the DROP syntaxes
 explain the usage of various Describe syntaxes

Sikkim Manipal University Page No. 52


RDBMS with MySQL Unit 3

3.2 CREATE DATABASE Syntax


CREATE DATABASE creates a database with the given name. To use this
statement, you need the CREATE privilege for the database. CREATE
SCHEMA is a synonym for CREATE DATABASE.
An error occurs if the database exists and you did not specify IF NOT
EXISTS.
create_specification options specify database characteristics. Database
characteristics are stored in the db.opt file in the database directory. The
CHARACTER SET clause specifies the default database character set. The
COLLATE clause specifies the default database collation.
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.

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


[create_specification] ...

create_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name

If you manually create a directory under the data directory (for example, with
mkdir), the server considers it as a database directory and is shown in the
output of SHOW_DATABASES.

Self Assessment Questions


1. ______________ is a synonym for CREATE DATABASE.

3.3 CREATE INDEX Syntax


Indexes are used to find rows with specific column values quickly. Without
an index, MySQL must begin with the first row and then read through the
entire table to find the relevant rows. The larger the table, the more is the
cost. If the table has an index for the columns in question, MySQL can
quickly determine the position to seek to in the middle of the data file without
having to look at all the data. If a table has 1,000 rows, this is at least 100

Sikkim Manipal University Page No. 53


RDBMS with MySQL Unit 3

times faster than reading sequentially. If you need to access most of the
rows, it is faster to read sequentially, because this minimizes disk seeks.
Most MySQL indexes (PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT)
are stored in B-trees. Exceptions are that indexes on spatial data types use
R-trees, and that MEMORY tables also support hash indexes.
MySQL uses indexes for these operations:
 To find the rows matching a WHERE clause quickly.
 To eliminate rows from consideration. If there is a choice between
multiple indexes, MySQL normally uses the index that finds the smallest
number of rows.
 To retrieve rows from other tables when performing joins. MySQL can
use indexes on columns more efficiently if they are declared as the
same type and size. In this context, VARCHAR and CHAR are
considered the same if they are declared as the same size. For
example, VARCHAR(10) and CHAR(10) are the same size, but
VARCHAR(10) and CHAR(15) are not.
Comparison of dissimilar columns may prevent use of indexes if values
cannot be compared directly without conversion. Suppose that a
numeric column is compared to a string column. For a given value such
as 1 in the numeric column, it might compare equal to any number of
values in the string column such as '1', ' 1', '00001', or '01.e1'. This rules
out use of any indexes for the string column.
 To find the MIN() or MAX() value for a specific indexed column key_col.
This is optimized by a preprocessor that checks whether you are using
WHERE key_part_N = constant on all key parts that occur before
key_col in the index. In this case, MySQL does a single key lookup for
each MIN() or MAX() expression and replaces it with a constant. If all
expressions are replaced with constants, the query returns at once. For
example:

SELECT MIN(key_part2),MAX(key_part2) FROM tbl_name WHERE


key_part1=10;

Sikkim Manipal University Page No. 54


RDBMS with MySQL Unit 3

 To sort or group a table if the sorting or grouping is done on a leftmost


prefix of a usable key (for example, ORDER BY key_part1, key_part2). If
all key parts are followed by DESC, the key is read in reverse order.
 In some cases, a query can be optimized to retrieve values without
consulting the data rows. If a query uses only columns from a table that
are numeric and that form a leftmost prefix for some key, the selected
values may be retrieved from the index tree for greater speed:

SELECT key_part3 FROM tbl_name WHERE key_part1=1

Suppose that you issue the following SELECT statement:

mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;

If a multiple-column index exists on col1 and col2, the appropriate rows can
be fetched directly. If separate single-column indexes exist on col1 and col2,
the optimizer will attempt to use the Index Merge optimization, or attempt
to find the most restrictive index by deciding which index finds fewer rows
and using that index to fetch the rows.
Index Merge optimization: The Index Merge method is used to retrieve
rows with several range scans and to merge their results into one. The
merge can produce unions, intersections, or unions-of-intersections of its
underlying scans. This access method merges index scans from a single
table; it does not merge scans across multiple tables.
CREATE INDEX is mapped to an ALTER TABLE statement to create
indexes. CREATE INDEX cannot be used to create a PRIMARY KEY; use
ALTER TABLE instead. Normally, you create all indexes on a table at the
time the table itself is created with CREATE TABLE. CREATE INDEX
enables you to add indexes to existing tables. A column list of the form
(col1,col2,...) creates a multiple-column index. Index values are formed by
concatenating the values of the given columns.
Indexes can be created that use only the leading part of column values,
using col_name(length) syntax to specify an index prefix length:
 Prefixes can be specified for CHAR, VARCHAR, BINARY, and
VARBINARY columns.

Sikkim Manipal University Page No. 55


RDBMS with MySQL Unit 3

 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.
 For spatial columns, prefix values cannot be given.
The statement shown here creates an index using the first 10 characters of
the name column:

CREATE INDEX part_of_name ON customer (name(10));

If names in the column usually differ in the first 10 characters, this index
should not be much slower than an index created from the entire name
column. Also, using column prefixes for indexes can make the index file
much smaller, which could save a lot of disk space and might also speed up
INSERT operations.
Prefix lengths are storage engine-dependent (for example, a prefix can be
up to 1000 bytes long for MyISAM tables, 767 bytes for InnoDB tables).
Note that prefix limits are measured in bytes, whereas the prefix length in
CREATE INDEX statements is interpreted as number of characters for 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.
FULLTEXT indexes are supported only for MyISAM tables and can include
only CHAR, VARCHAR, and TEXT columns. Indexing always happens over
the entire column; column prefix indexing is not supported and any prefix
length is ignored if specified.
In MySQL 5.1:
 You can add an index on a column that can have NULL values only if
you are using the MyISAM, InnoDB, or MEMORY storage engine.
 You can add an index on a BLOB or TEXT column only if you are using
the MyISAM, 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

Sikkim Manipal University Page No. 56


RDBMS with MySQL Unit 3

descending index value storage. Currently, they are parsed but ignored;
index values are always stored in ascending order.

Self Assessment Questions


2. Database characteristics are stored in the ___ file in the database
directory.
3. BLOB and TEXT columns also can be indexed, but a ______ length
must be given.

3.4 CREATE TABLE Syntax


CREATE TABLE creates a table with the given name. You must have the
CREATE privilege for the table.
By default, the table is created in the default database. An error occurs if the
table exists, if there is no default database, or if the database does not exist.
The table name can be specified as db_name.tbl_name to create the table
in a specific database. This works regardless of whether there is a default
database, assuming that the database exists. If you use quoted identifiers,
quote the database and table names separately. For example, write
`mydb`.`mytbl`, not `mydb.mytbl`.
You can use the TEMPORARY keyword when creating a table. A
TEMPORARY table is visible only to the current connection, and is dropped
automatically when the connection is closed. This means that two different
connections can use the same temporary table name without conflicting with
each other or with an existing non-TEMPORARY table of the same name.
(The existing table is hidden until the temporary table is dropped.) To create
temporary tables, you must have the CREATE TEMPORARY TABLES
privilege.
Note: CREATE TABLE does not automatically commit the current active
transaction if you use the TEMPORARY keyword.
The keywords IF NOT EXISTS prevent an error from occurring if the table
exists. However, there is no verification that the existing table has a
structure identical to that indicated by the CREATE TABLE statement.

Sikkim Manipal University Page No. 57


RDBMS with MySQL Unit 3

Note: If you use IF NOT EXISTS in a CREATE TABLE ... SELECT


statement, any rows selected by the SELECT part are inserted regardless of
whether the table already exists.
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)
tbl_name.frm
file
tbl_name.MYD Data file
tbl_name.MYI Index file

CREATE TABLE Syntax

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name


(create_definition,...)
[table_option] ...
[partition_options]

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

OR

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name


{ LIKE old_tbl_name | (LIKE old_tbl_name) }

Sikkim Manipal University Page No. 58


RDBMS with MySQL Unit 3

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] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
[COMMENT 'string'] [reference_definition]
[COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
[STORAGE {DISK|MEMORY|DEFAULT}]

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

index_type:
USING {BTREE | HASH | RTREE}

index_option:
KEY_BLOCK_SIZE [=] value
| index_type
| WITH PARSER parser_name

reference_definition:
REFERENCES tbl_name (index_col_name,...)
[MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

Sikkim Manipal University Page No. 59


RDBMS with MySQL Unit 3

select_statement:
[IGNORE | REPLACE] [AS] SELECT ... (Some legal select statement)

Storage Engine 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
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.
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 nor NOT NULL is specified, the column is treated as
though NULL had been specified.
 An integer or floating-point column can have the additional attribute
AUTO_INCREMENT. When you insert a value of NULL (recommended)
or 0 into an indexed AUTO_INCREMENT column, the column is set to
the next sequence value. Typically this is value+1, where value is the
largest value for the column currently in the table. AUTO_INCREMENT
sequences begin with 1.
To retrieve an AUTO_INCREMENT value after inserting a row, use the
LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function.
If the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled, you can store
0 in AUTO_INCREMENT columns as 0 without generating a new sequence
value.
Note: There can be only one AUTO_INCREMENT column per table, it must
be indexed, and it cannot have a DEFAULT value. An AUTO_INCREMENT
column works properly 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 an
AUTO_INCREMENT column that contains 0.

Sikkim Manipal University Page No. 60


RDBMS with MySQL Unit 3

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 WHERE auto_col IS NULL

Character data types (CHAR, VARCHAR, TEXT) can include CHARACTER


SET and COLLATE attributes to specify the character set and collation for
the column. CHARSET is a synonym for CHARACTER SET.
CREATE TABLE t (c CHAR(20) CHARACTER SET utf8 COLLATE utf8_bin);

MySQL 5.1 interprets length specifications in character column definitions in


characters.
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 as NOW() or
CURRENT_DATE. The exception is that you can specify
CURRENT_TIMESTAMP as the default for a TIMESTAMP column.
Note: BLOB and TEXT columns cannot be assigned a default value.
 A comment for a column can be specified with the COMMENT option, up
to 255 characters long. The comment is displayed by the SHOW
CREATE TABLE and SHOW FULL COLUMNS statements.
 Beginning with MySQL Cluster NDB 6.2.5 and MySQL Cluster NDB
6.3.2, it is also possible to specify a data storage format for individual
columns of NDB tables using COLUMN_FORMAT. Allowable column
formats are FIXED, DYNAMIC, and DEFAULT. FIXED is used to specify
fixed-width storage, DYNAMIC allows the column to be variable-width,
and DEFAULT causes the column to use fixed-width or variable-width
storage as determined by the column's data type (possibly overridden by
a ROW_FORMAT specifier).
For NDB tables, the default value for COLUMN_FORMAT is DEFAULT.
COLUMN_FORMAT currently has no effect on columns of tables using
storage engines other than NDB.
 For NDB tables, beginning with MySQL Cluster NDB 6.2.5 and MySQL
Cluster NDB 6.3.2, it is also possible to specify whether the column is
Sikkim Manipal University Page No. 61
RDBMS with MySQL Unit 3

stored on disk or in memory by using a STORAGE clause. STORAGE


DISK causes the column to be stored on disk, and STORAGE MEMORY
causes in-memory storage to be used. The CREATE TABLE statement
used must still include a TABLESPACE clause:

mysql> CREATE TABLE t1 (


-> c1 INT STORAGE DISK,
-> c2 INT STORAGE MEMORY
-> ) ENGINE NDB;
ERROR 1005 (HY000): Can't create table 'c.t1' (errno: 140)

mysql> CREATE TABLE t1 (


-> c1 INT STORAGE DISK,
-> c2 INT STORAGE MEMORY
-> ) TABLESPACE ts_1 ENGINE NDB;
Query OK, 0 rows affected (1.06 sec)

For NDB tables, STORAGE DEFAULT is equivalent to STORAGE


MEMORY.
The STORAGE clause has no effect on tables using storage engines other
than NDB.
 KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY
can also be specified as just KEY 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, a UNIQUE index
allows multiple NULL values for columns that can contain NULL.
 A PRIMARY KEY is a unique index where all key columns must be
defined as NOT NULL. If they are not explicitly declared as NOT NULL,
MySQL declares them so implicitly (and silently). A table can have only
one PRIMARY KEY. If you do not have a PRIMARY KEY and an
application asks for the PRIMARY KEY in your tables, MySQL returns
the first UNIQUE index that has no NULL columns as the PRIMARY
KEY.
 In the created table, a PRIMARY KEY is placed first, followed by all
UNIQUE indexes, and then the non-unique indexes. This helps the

Sikkim Manipal University Page No. 62


RDBMS with MySQL Unit 3

MySQL optimizer to prioritize which index to use and also more quickly
to detect duplicated UNIQUE keys.
 A PRIMARY KEY can be a multiple-column index. However, you cannot
create a multiple-column index using the PRIMARY KEY key attribute in
a column specification. Doing so only marks that single column as
primary. You must use a separate PRIMARY KEY(index_col_name, ...)
clause.
 If a PRIMARY KEY or UNIQUE index consists of only one column that
has an integer type, you can also refer to the column as _rowid in
SELECT statements.
 In MySQL, the name of a PRIMARY KEY is PRIMARY. 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 using SHOW
INDEX FROM tbl_name.
 Some storage engines allow you to specify an index type when creating
an index. The syntax for the index_type specifier is USING type_name.
Example:

CREATE TABLE lookup


(id INT, INDEX USING BTREE (id))
ENGINE = MEMORY;

 In MySQL 5.1, only the MyISAM, InnoDB, and MEMORY storage


engines support indexes on columns that can have NULL values. In
other cases, you must declare indexed columns as NOT NULL or an
error results.
 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

Sikkim Manipal University Page No. 63


RDBMS with MySQL Unit 3

BINARY, VARBINARY, and BLOB columns. Indexing only a prefix of


column values like this can make the index file much smaller. Only the
MyISAM and InnoDB storage engines support indexing on BLOB and
TEXT columns.
 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.
 When you use ORDER BY or GROUP BY on a TEXT or BLOB column
in a SELECT, the server sorts values using only the initial number of
bytes indicated by the max_sort_length system variable.
 InnoDB tables support checking of foreign key constraints. Note that the
FOREIGN KEY syntax in InnoDB is more restrictive than the syntax
presented for the CREATE TABLE statement at the beginning of this
section: The columns of the referenced table must always be explicitly
named. InnoDB supports both ON DELETE and ON UPDATE actions on
foreign keys.
There is a hard limit of 4096 columns per table, but the effective maximum
may be less for a given table. The exact limit depends on several interacting
factors, listed in the following discussion.
 Every table has a maximum row size of 65,535 bytes. This maximum
applies to all storage engines, but a given engine might have additional
constraints that result in a lower effective maximum row size.
The maximum row size constrains the number of columns because the
total width of all columns cannot exceed this size. For example, utf8
characters require up to three bytes per character, so for a CHAR(255)
CHARACTER SET utf8 column, the server must allocate 255 × 3 = 765
bytes per value. Consequently, a table cannot contain more than 65,535
/ 765 = 85 such columns.
Storage for variable-length columns includes length bytes, which are
assessed against the row size. For example, a VARCHAR(255)
CHARACTER SET utf8 column takes two bytes to store the length of the
value, so each value can take up to 767 bytes.

Sikkim Manipal University Page No. 64


RDBMS with MySQL Unit 3

BLOB and TEXT columns count from one to four plus eight bytes each
toward the row-size limit because their contents are stored separately.
Declaring columns NULL can reduce the maximum number of columns
allowed. NULL columns require additional space in the row to record
whether or not their values are NULL.
For MyISAM tables, each NULL column takes one bit extra, rounded up
to the nearest byte.
 The maximum row length in bytes can be calculated as follows:
Row length = 1
+ (sum of column lengths)
+ (number of NULL columns + delete_flag + 7)/8
+ (number of variable-length columns)

delete_flag is 1 for tables with static row format. Static tables use a bit in the
row record for a flag that indicates whether the row has been deleted.
delete_flag is 0 for dynamic tables because the flag is stored in the dynamic
row header.
These calculations do not apply for InnoDB tables, for which storage size is
no different for NULL columns than for NOT NULL columns.
 Each table has an .frm file that contains the table definition. The .frm file
size limit is fixed at 64KB. If a table definition reaches this size, no more
columns can be added. The expression that checks information to be
stored in the .frm file against the limit looks like this:

if (info_length+(ulong) create_fields.elements*FCOMP+288+
n_length+int_length+com_length > 65535L || int_count > 255)

The relevant factors in this expression are:


o info_length is space needed for “screens.” This is related to MySQL's
Unireg heritage.
o create_fields.elements is the number of columns.
o FCOMP is 17.
o n_length is the total length of all column names, including one byte
per name as a separator.
o int_length is related to the list of values for SET and ENUM columns.

Sikkim Manipal University Page No. 65


RDBMS with MySQL Unit 3

o com_length is the total length of column and table comments.


Thus, using long column names can reduce the maximum number of
columns, as can the inclusion of ENUM or SET columns, or use of
column or table comments.
The TABLESPACE and STORAGE table options were both introduced in
MySQL 5.1.6. In MySQL 5.1, they are employed only with NDBCLUSTER
tables. The tablespace named tablespace_name must already have been
created using CREATE TABLESPACE. STORAGE determines the type of
storage used (disk or memory), and can be one of DISK, MEMORY, or
DEFAULT.
TABLESPACE ... STORAGE DISK assigns a table to a MySQL Cluster Disk
Data tablespace.
Important Note: A STORAGE clause cannot be used in a CREATE TABLE
statement without a TABLESPACE clause.
The ENGINE table option specifies the storage engine for the table.
The ENGINE table option takes the storage engine names shown in the
table 3.1.
Table 3.1: Storage Engines and Descriptions
Storage Engine Description
ARCHIVE The archiving storage engine
CSV Tables that store rows in comma-separated values
format.
EXAMPLE An example engine.
FEDERATED Storage engine that accesses remote tables.
HEAP This is a synonym for MEMORY.
ISAM (OBSOLETE) Not available in MySQL 5.1. If you are upgrading to
MySQL 5.1 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.
MEMORY The data for this storage engine is stored only in
memory.

Sikkim Manipal University Page No. 66


RDBMS with MySQL Unit 3

MERGE A collection of MyISAM tables used as one table. Also


known as MRG_MyISAM.
MyISAM The binary portable storage engine that is the default
storage engine used by MySQL.
NDBCLUSTER Clustered, fault-tolerant, memory-based tables. Also
known as NDB.

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 non-transactional (to get
more speed). In MySQL 5.1, 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.
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.1, this works for MyISAM, MEMORY, and InnoDB
tables. It also works for ARCHIVE tables as of MySQL 5.1.6. To set the
first auto-increment value for engines that do not support the
AUTO_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 in
CREATE TABLE statements, you can also use ALTER TABLE tbl_name
AUTO_INCREMENT = N to reset the AUTO_INCREMENT value. The

Sikkim Manipal University Page No. 67


RDBMS with MySQL Unit 3

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 the
MAX_ROWS and AVG_ROW_LENGTH options to decide how big the
resulting table is. If you don't specify either option, the maximum size for
MyISAM 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 the
myisam_data_pointer_size system variable. If you want all your tables to
be able to grow above the default limit and are willing to have your
tables slightly slower and larger than necessary, you can increase the
default pointer size by setting this variable. Setting the value to 7 allows
table sizes up to 65,536TB.
 [DEFAULT] CHARACTER SET: Specify a default character set for the
table. CHARSET is a synonym for CHARACTER SET. If the character
set name is DEFAULT, 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 60 characters long.
 CONNECTION: The connection string for a FEDERATED table.
 DATA DIRECTORY, INDEX DIRECTORY: By using DATA
DIRECTORY='directory' or INDEX DIRECTORY='directory' you can
specify where the MyISAM storage engine should put a table's data file
and index file. The directory must be the full pathname to the directory,
not a relative path.

Sikkim Manipal University Page No. 68


RDBMS with MySQL Unit 3

If a MyISAM table is created with no DATA DIRECTORY option, the .MYD


file is created in the database directory. By default, if MyISAM finds an
existing .MYD file in this case, it overwrites it. The same applies to .MYI files
for tables created with no INDEX DIRECTORY option. As of MySQL 5.1.23,
to suppress this behavior, start the server with the --keep_files_on_create
option, in which case MyISAM will not overwrite existing files and returns an
error instead.
If a MyISAM table is created with a DATA DIRECTORY or INDEX
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.
 DELAY_KEY_WRITE: Set this to 1 if you want to delay key updates for
the table until the table is closed.
 INSERT_METHOD: If you want to insert data into a MERGE table, you
must specify with INSERT_METHOD the table into which the row should
be inserted. INSERT_METHOD is an option useful for MERGE tables
only. Use a value of FIRST or LAST to have inserts go to the first or last
table, or a value of NO to prevent inserts.
 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
allowed to change the value if necessary. A value of 0 indicates that the
default value should be used. Individual index definitions can specify a
KEY_BLOCK_SIZE value of their own to override the table value.
KEY_BLOCK_SIZE was added in MySQL 5.1.10.
 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.
 MIN_ROWS: The minimum number of rows you plan to store in the
table.
 PACK_KEYS: PACK_KEYS takes effect only with MyISAM 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 to DEFAULT tells the storage engine to pack
only long CHAR, VARCHAR, BINARY, or VARBINARY columns.

Sikkim Manipal University Page No. 69


RDBMS with MySQL Unit 3

If you do not use PACK_KEYS, the default is to pack strings, but not
numbers. If you use PACK_KEYS=1, numbers are packed as well.
When packing binary number keys, MySQL uses prefix compression:
o Every key needs one extra byte to indicate how many bytes of the
previous key are the same for the next key.
o 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 have NULL
values. (In this case, the packed key length is stored in the same byte that is
used to mark if a key is NULL.)
 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 be FIXED or DYNAMIC for static or variable-
length row format. myisampack sets the type to COMPRESSED.
Note: When 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 to SHOW TABLE
STATUS is the actual row format used. This may differ from the value in the
Create_options column because the original CREATE TABLE definition is
retained during creation.
 UNION: UNION is used when you want to access a collection of
identical MyISAM tables as one. This works only with MERGE tables.

Sikkim Manipal University Page No. 70


RDBMS with MySQL Unit 3

You must have SELECT, UPDATE, and DELETE privileges for the
tables you map to a MERGE table.
 partition_options can be used to control partitioning of the table created
with CREATE TABLE.
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.1 are shown in
the following list:
o HASH(expr): Hashes one or more columns to create a key for
placing and locating rows. 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.
o KEY(column_list): This is similar to HASH, except that MySQL
supplies the hashing function so as to guarantee an even data
distribution. The column_list argument is simply a list of table
columns.
o 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 by HASH. That is, the partition
number is found using the & operator rather than the modulus. You
may not use either VALUES LESS THAN or VALUES IN clauses
with PARTITION BY KEY.
o RANGE: In this case, expr shows a range of values using a set
of VALUES LESS THAN operators. When using range
partitioning, you must define at least one partition using VALUES
LESS THAN. You cannot use VALUES IN with range partitioning.
VALUES LESS THAN can be used with either a literal value or
an expression that evaluates to a single value.
o LIST(expr): 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

Sikkim Manipal University Page No. 71


RDBMS with MySQL Unit 3

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 to RANGE, except that only VALUES IN may be used
to specify allowable values for each partition. When using list
partitioning, you must define at least one partition using VALUES
IN. You cannot use VALUES LESS THAN with PARTITION BY
LIST.
o The number of partitions may optionally be specified with a
PARTITIONS num clause, where num is the number of
partitions. If both this clause and any PARTITION clauses are
used, num must be equal to the total number of any partitions
that are declared using PARTITION clauses.
o 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 by
HASH or KEY. Either of these may be LINEAR. These work in
the same way as previously described for the equivalent
partitioning types. (It is not possible to subpartition by LIST or
RANGE.)
The number of subpartitions can be indicated using the
SUBPARTITIONS keyword followed by an integer value.
o MySQL 5.1.12 introduces rigorous checking of the value used in
a PARTITIONS or SUBPARTITIONS clause. Beginning with this
version, this value must adhere to the following rules:
 The value must be a positive, non-zero integer.
 No leading zeroes are permitted.
 The value must be an integer literal, and cannot not be an
expression.
 Each partition may be individually defined using a partition_definition
clause. The individual parts making up this clause are as follows:
 PARTITION partition_name: This specifies a logical name for the
partition.
 A VALUES clause: For range partitioning, each partition must
include a VALUES LESS THAN clause; for list partitioning, you must
specify a VALUES IN clause for each partition. This is used to
determine which rows are to be stored in this partition.

Sikkim Manipal University Page No. 72


RDBMS with MySQL Unit 3

 An optional COMMENT clause may be used to specify a string that


describes the partition.
 DATA DIRECTORY and INDEX DIRECTORY may be used to indicate
the directory where, respectively, the data and indexes for this partition
are to be stored. Both the data_dir and the index_dir must be absolute
system pathnames.
DATA DIRECTORY and INDEX DIRECTORY behave in the same way
as in the CREATE TABLE statement's table_option clause as used for
MyISAM 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 and INDEX DIRECTORY options
are not supported for individual partitions or subpartitions. Beginning
with MySQL 5.1.24, these options are ignored on Windows, except that
a warning is generated. (Bug#30459)
 MAX_ROWS and MIN_ROWS may be used to specify, respectively, the
maximum and minimum number of rows to be stored in the partition. The
values for max_number_of_rows and min_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 optional TABLESPACE clause may be used to designate a
tablespace for the partition. Used for MySQL Cluster only.
 The partitioning handler accepts a [STORAGE] ENGINE option for both
PARTITION and SUBPARTITION. Currently, the only way in which this
can be used is to set all partitions or all subpartitions to the same
storage engine, and an attempt to set different storage engines for
partitions or subpartitions in the same table will give rise to the error
ERROR 1469 (HY000): The mix of handlers in the partitions is not
allowed in this version of MySQL. We expect to lift this restriction on
partitioning in a future MySQL release.
 The NODEGROUP option can be used to make this partition act as part
of the node group identified by node_group_id. This option is applicable
only to MySQL Cluster.

Sikkim Manipal University Page No. 73


RDBMS with MySQL Unit 3

 The partition definition may optionally contain one or more


subpartition_definition clauses. Each of these consists at a minimum of
the SUBPARTITION name, where name is an identifier for the
subpartition. Except for the replacement of the PARTITION keyword with
SUBPARTITION, the syntax for a subpartition definition is identical to
that for a partition definition.
 Subpartitioning must be done by HASH or KEY, and can be done only
on RANGE or LIST partitions.
 Partitions can be modified, merged, added to tables, and dropped from
tables.
 You can create one table from another by adding a SELECT statement
at the end of the CREATE TABLE statement:

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

 MySQL creates new columns for all elements in the SELECT. For
example:
mysql> CREATE TABLE test (a INT NOT NULL
AUTO_INCREMENT,
-> PRIMARY KEY (a), KEY(b))
-> ENGINE=MyISAM SELECT b,c FROM test2;

This creates a MyISAM table with three columns, a, b, and c. Notice


that the columns from the SELECT statement are appended to the
right side of the table, not overlapped onto it.

Consider the following example:

mysql> SELECT * FROM foo;


+---+
|n|
+---+
|1|
+---+

mysql> CREATE TABLE bar (m INT) SELECT n FROM foo;


Query OK, 1 row affected (0.02 sec)
Records: 1 Duplicates: 0 Warnings: 0

Sikkim Manipal University Page No. 74


RDBMS with MySQL Unit 3

mysql> SELECT * FROM bar;


+------+---+
|m |n|
+------+---+
| NULL | 1 |
+------+---+
1 row in set (0.00 sec)

For each row in table foo, a row is inserted in bar with the values
from foo and default values for the new columns.
In a table resulting from CREATE TABLE ... SELECT, columns
named only in the CREATE TABLE part come first. Columns named
in both parts or only in the SELECT part come after that. The data
type of SELECT columns can be overridden by also specifying the
column in the CREATE TABLE part.
If any errors occur while copying the data to the table, it is
automatically dropped and not created.
 CREATE TABLE ... SELECT does not automatically create any
indexes for you. This is done intentionally to make the statement as
flexible as possible. If you want to have indexes in the created table,
you should specify these before the SELECT statement:

mysql> CREATE TABLE bar (UNIQUE (n)) SELECT n FROM foo;

3.4.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.
 TIMESTAMP display sizes are discarded.
Also note that TIMESTAMP columns are NOT NULL by default.
 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.

Sikkim Manipal University Page No. 75


RDBMS with MySQL Unit 3

 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.
 If strict SQL mode is not enabled, a VARCHAR column with a length
specification greater than 65535 is converted to TEXT, and a
VARBINARY column with a length specification greater than 65535
is converted to BLOB. Otherwise, an error occurs in either of these
cases.
 Specifying the CHARACTER SET binary attribute for a character
data type causes the column to be created as the corresponding
binary data type: CHAR becomes BINARY, VARCHAR becomes
VARBINARY, and TEXT becomes BLOB. For the ENUM and SET
data types, this does not occur; they are created as declared.
Suppose that you specify a table using this definition:

CREATE TABLE t
(
c1 VARCHAR(10) CHARACTER SET binary,
c2 TEXT CHARACTER SET binary,
c3 ENUM('a','b','c') CHARACTER SET binary
);

The resulting table has this definition:


CREATE TABLE t
(
c1 VARBINARY(10),
c2 BLOB,
c3 ENUM('a','b','c') CHARACTER SET binary
);

Self Assessment Questions


4. A _______ table is visible only to the current connection, and is dropped
automatically when the connection is closed.
5. _______ does not apply to the BLOB or TEXT types.

Sikkim Manipal University Page No. 76


RDBMS with MySQL Unit 3

3.5 ALTER DATABASE Syntax


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.

ALTER {DATABASE | SCHEMA} [db_name]


alter_specification ...
ALTER {DATABASE | SCHEMA} db_name
UPGRADE DATA DIRECTORY NAME

alter_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name

The CHARACTER SET clause changes the default database character set.
The COLLATE clause changes the default database collation.

You can see what character sets and collations are available using,
respectively, the SHOW CHARACTER SET and SHOW COLLATION
statements.
The database name can be omitted from the first syntax, in which case the
statement applies to the default database.
The syntax that includes the UPGRADE DATA DIRECTORY NAME clause
was added in MySQL 5.1.23. It updates the name of the directory
associated with the database to use the encoding implemented in MySQL
5.1 for mapping database names to database directory names. This clause
is for use under these conditions:
 It is intended when upgrading MySQL to 5.1 or later from older
versions.
 It is intended to update a database directory name to the current
encoding format if the name contains special characters that need
encoding.
 The statement is used by mysqlcheck (as invoked by
mysql_upgrade).
For example,if a database in MySQL 5.0 has a name of a-b-c, the name
contains instance of the „-‟ character. In 5.0, the database directory is also

Sikkim Manipal University Page No. 77


RDBMS with MySQL Unit 3

named a-b-c, which is not necessarily safe for all filesystems. In MySQL 5.1
and up, the same database name is encoded as a@002db@002dc to
produce a filesystem-neutral directory name.

3.6 ALTER TABLE Syntax


You can later an existing table with the ALTER TABLE command, which
allows you to add, remove, or modify table fields or indices without the need
to re-create the entire table. The syntax is given below:

ALTER TABLE table-name (action field-definition,


action field definition, …);

The action component here can be any of the keywords ADD, DROP,
ALTER, or CHANGE, and is followed by a field definition similar to that used
by the CREATE TABLE command. This definition consists of the name of
the field to be modified and (depending on the operation) a field definition
consisting of a new field name, type, and constraints.

Given below is an example which first creates a table and then adds a new
column to it.

Sikkim Manipal University Page No. 78


RDBMS with MySQL Unit 3

The following example adds a primary key column to the existing members
table:

Sikkim Manipal University Page No. 79


RDBMS with MySQL Unit 3

The following example changes the name and type of an existing field:

The following example shows a query for deleting a field or a key.

You can use the ALTER TABLE command to rename a table as shown
below:

Sikkim Manipal University Page No. 80


RDBMS with MySQL Unit 3

You can also use the equivalent RENAME TABLE command as shown
below:

You can set (or remove) a default value for a field with the SET DEFAULT
and DROP DEFAULT clauses, and you can control the position of fields with
the FIRST and AFTER clauses to the ALTER TABLE command.

Sikkim Manipal University Page No. 81


RDBMS with MySQL Unit 3

Adding an AUTO_INCREMENT field to a table causes all existing records in


that table to be automatically numbered. For example you have a table
named „movies‟ as shown below:

Now you decide to add an AUTO_INCREMENT primary key to each field as


follows:

When adding a UNIQUE key to a table that contains duplicate values on


that key, you can control how MySQL handles the situation (either delete all
duplicate records or abort the alteration) by including or omitting the optional
IGNORE clause. Consider the following table, which contains two records
with the same value in the name field:

Sikkim Manipal University Page No. 82


RDBMS with MySQL Unit 3

Now, if you were to set the name field to be UNIQUE, MySQL would return
an error about duplicate values in that field.

However, if you specify the IGNORE clause to the ALTER TABLE


command, then MySQL removes all records with duplicate values on that
key from the table, retaining only the first instance, as the shown in the
following illustration:

Sikkim Manipal University Page No. 83


RDBMS with MySQL Unit 3

Self Assessment Questions


6. For all engines, a _____ index allows multiple NULL values for columns
that can contain NULL.
7. Each table has an ____ file that contains the table definition.

3.7 DROP DATABASE Syntax


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.

DROP {DATABASE | SCHEMA} [IF EXISTS] db_name

Important Note: When a database is dropped, user privileges on the


database are not automatically dropped.
 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:

Sikkim Manipal University Page No. 84


RDBMS with MySQL Unit 3

 All files with these extensions:


.BAK .DAT .HSH .MRG
.MYD .MYI .TRG .TRN
.db .frm .ibd .ndb
.par

 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.

3.8 DROP INDEX Syntax


If you find you no longer have any need of an index, you can nuke it with the
DROP index command.
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.
Syntax:

DROP INDEX index-name ON table-name

Example: The following command deletes the username index created on


uname column.

mysql> DROP INDEX username on sysusers;

Beginning with MySQL 5.1.7, indexes on variable-width columns are


dropped online; that is, dropping the indexes does not require any copying
or locking of the table. This is done automatically by the server whenever it
determines that it is possible to do so; you do not have to use any special
SQL syntax or server options to cause it to happen.

3.9 DROP TABLE Syntax


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,

Sikkim Manipal University Page No. 85


RDBMS with MySQL Unit 3

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.

DROP [TEMPORARY] TABLE [IF EXISTS]


tbl_name [, tbl_name] ...
[RESTRICT | CASCADE]

Important Note: When a table is dropped, user privileges on the table are
not automatically dropped.
Note that for a partitioned table, DROP TABLE permanently removes the
table definition, all of its partitions, and all of the data which was stored in
those partitions. It also removes the partitioning definition (.par) file
associated with the dropped table.
Use IF EXISTS to prevent an error from occurring for tables that do not
exist. A NOTE is generated for each non-existent table when using IF
EXISTS.
RESTRICT and CASCADE are allowed to make porting easier. In MySQL
5.1, they do nothing.
Note: DROP TABLE automatically commits the current active transaction,
unless you use the TEMPORARY keyword.
The TEMPORARY keyword has the following effects:
 The statement drops only 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.

3.10 DESCRIBE syntax


You can obtain the information on the structure of a table – its fields, field
types, keys, and defaults – with the DESCRIBE command.

Sikkim Manipal University Page No. 86


RDBMS with MySQL Unit 3

DESCRIBE provides information about the columns in a table. It is a


shortcut for SHOW COLUMNS FROM. These statements also display
information for views.
col_name can be a column name, or a string containing the SQL “%” and “_”
wildcard characters to obtain output only for the columns with names
matching the string. There is no need to enclose the string within quotes
unless it contains spaces or other special characters.
The DESCRIBE statement is provided for compatibility with Oracle.

Syntax:
{DESCRIBE | DESC} tbl_name [col_name | wild]

3.11 Summary
This unit covers the following topics with respect to data definition language
statements in MySQL:
1. CREATE DATABASE: This topic covers the starting point of creating
the databases before any data objects are built into the databases. The
user must first create a database and build objects like tables, views,
stored procedures and so on inside the database. It gives the syntax
associated with creation of these databases within the MySQL server.
2. CREATE INDEX: The importance and syntaxes used in the creation of
indexes is mentioned in this topic.
Sikkim Manipal University Page No. 87
RDBMS with MySQL Unit 3

3. CREATE TABLE: Tables are the basic data structures used to store
data. The syntaxes and variations of creating the tables are discussed
here.
4. ALTER DATABASE: Database modifications and the respective
syntaxes are described along with suitable examples are discussed.
5. ALTER TABLE: Modifications to the existing tables and the
corresponding syntaxes are described with suitable examples are
discussed here.
6. DROP DATABASE: Databases can be dropped as and when required.
The details of this is discussed.
7. DROP INDEX: Indexes can be dropped depending on the requirement
and size of the database objects.
8. DROP TABLE: Tables Indexes can be dropped depending on the
requirement of the user or application.
9. DESCRIBE: Anyone who needs to know the structure and data types of
the database tables can use this command for this purpose.

3.12 Terminal Questions


1. Write about the operations supported by indexes in MySQL
2. Write and explain the ALTER DATABASE Syntax
3. Write the SQL statements to perform the following actions using ALTER
TABLE command:
a. Create a table and then add a new column to it.
b. Add a primary key column to an existing table.
c. Change the name and type of an existing field.

3.13 Answers
Self Assessment Questions
1. CREATE SCHEMA
2. db.opt
3. prefix
4. TEMPORARY
5. DEFAULT
6. UNIQUE
7. .frm

Sikkim Manipal University Page No. 88


RDBMS with MySQL Unit 3

Terminal Questions
1.
 To find the rows matching a WHERE clause quickly.
 To eliminate rows from consideration.
 To retrieve rows from other tables when performing joins.
 To find the MIN() or MAX() value for a specific indexed column
key_col.
(Refer Section 3.3)
2.
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.
ALTER {DATABASE | SCHEMA} [db_name]
alter_specification ...
ALTER {DATABASE | SCHEMA} db_name
UPGRADE DATA DIRECTORY NAME

alter_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name

The CHARACTER SET clause changes the default database character set.
The COLLATE clause changes the default database collation.
You can see what character sets and collations are available using,
respectively, the SHOW CHARACTER SET and SHOW COLLATION
statements.
The database name can be omitted from the first syntax, in which case the
statement applies to the default database.
(Refer Section 3.5)
3.
a. CREATE TABLE members(mid INT(3), mname CHAR(8), mpass
VARCHAR(25));
ALTER TABLE members ADD email VARCHAR(255) NOT NULL;
b. ALTER TABLE members ADD PRIMARY KEY(email);
c. ALTER TABLE members CHANGE mid id INT(8) AUTO_INCREMENT
UNIQUE;
Sikkim Manipal University Page No. 89
RDBMS with MySQL Unit 3

(Refer Section 3.6)

Sikkim Manipal University Page No. 90

Das könnte Ihnen auch gefallen