Sei sulla pagina 1di 2

Explanation

Primary key as index


Consider you have a TBL_STUDENT table and you want STUDENT_ID as primary key:

ALTER TABLE `tbl_student` ADD PRIMARY KEY (`student_id`)


Above statement adds a primary key, which means that indexed values must be unique and
cannot be NULL.

Specify index name


ALTER TABLE `tbl_student` ADD INDEX student_index (`student_id`)
Above statement will create an ordinary index with student_index name.
Create unique index
ALTER TABLE `tbl_student` ADD UNIQUE student_unique_index (`student_id`)
Here, student_unique_index is the index name assigned to STUDENT_ID and creates an
index for which values must be unique (here null can be accepted).
Fulltext option
ALTER TABLE `tbl_student` ADD FULLTEXT student_fulltext_index (`student_id`)
Above statement will create the Fulltext index name with student_fulltext_index, for which
you need MyISAM Mysql Engine.
How to remove indexes ?
DROP INDEX `student_index` ON `tbl_student`
How to check available indexes?
SHOW INDEX FROM `tbl_student`

Here is the example to add index in an existing table.

mysql> ALTER TABLE testalter_tbl ADD INDEX (c);

to drop the index

mysql> ALTER TABLE testalter_tbl DROP INDEX (c);

ALTER Command to add and drop PRIMARY


KEY:
You can add primary key as well in the same way. But make sure Primary
Key works on columns, which are NOT NULL.

Here is the example to add primary key in an existing table. This will make
a column NOT NULL first and then add it as a primary key.
mysql> ALTER TABLE testalter_tbl MODIFY i INT NOT NULL;
mysql> ALTER TABLE testalter_tbl ADD PRIMARY KEY (i);

You can use ALTER command to drop a primary key as follows:

mysql> ALTER TABLE testalter_tbl DROP PRIMARY KEY;

Displaying INDEX Information:


You can use SHOW INDEX command to list out all the indexes associated
with a table. Vertical-format output (specified by \G) often is useful with
this statement, to avoid long line wraparound:

Try out the following example:

mysql> SHOW INDEX FROM table_name\G

The statement shown here creates an index using the first 10 characters of the name column (assuming
that name has a nonbinary string type):

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

Potrebbero piacerti anche