Simple tutorial for Unique Indexes in MySQL _ MySQL

Source: Internet
Author: User
Tags mysql index
This article mainly introduces a simple tutorial on the unique index in MySQL, which is the basic knowledge in MySQL getting started, for more information, see the UNIQUE mysql index UNIQUE. it is generally used for non-duplicate data fields. we often set the id in the data table as the UNIQUE index UNIQUE, next I will introduce how to use the UNIQUE index UNIQUE in mysql.
The purpose of creating a unique index is not to speed up access, but to avoid data duplication. A unique index can have multiple values but the values of the index column must be unique. The value of the index column can have null values. If you can determine that a data column will only contain different values, you should use the keyword UNIQUE when creating an index for this data column.

Define it as a unique index.


Directly set when creating a table:


DROP TABLE IF EXISTS `student`;CREATE TABLE `student` (`stu_id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) DEFAULT NULL,PRIMARY KEY (`stu_id`),UNIQUE KEY `UK_student_name` (`name`)) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;


Create a unique index:


create unique index UK_student_name on student (name);


Add constraints after creating a table:


alter table student add constraint uk_student_name unique (name);


If you do not need a unique index, you can delete it like this.


mysql> ALTER TABLE student DROP INDEX name;



Query OK, 0 rows affected (0.85 sec)



If you want to add an index

alter table user add unique index(user_id,user_name);


The above is the only index in MySQL simple learning tutorial _ MySQL content, for more information, please follow the PHP Chinese network (www.php1.cn )!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.