Home >Database >Mysql Tutorial >What is the use of sql unique constraint?

What is the use of sql unique constraint?

清浅
清浅Original
2019-05-09 09:27:556851browse

The role of the unique constraint in SQL is to ensure that each record has a unique identifier so that there are no two identical record values ​​in the column; the primary key of the table is a unique constraint, but the primary key only There can be one, so if the data in other columns is not allowed to be repeated, a unique constraint can be established.

What is the use of sql unique constraint?

#The role of the unique constraint in SQL is to ensure that each record has a unique identifier so that there are no two identical record values ​​in the column.

Unique constraint

The unique constraint in SQL prevents the same two record values ​​​​in a specific column, that is to say, it is used to ensure that each record Each has a unique identifier so that there are no duplicate values ​​in the column. The primary key of the table is a unique constraint, but there can only be one primary key, so if the data in other columns is not allowed to be repeated, a unique constraint can be established.

Create unique constraints

For example, the following SQL creates a new table named CUSTOMERS and adds five columns. Here, the AGE column is set to be unique, so there cannot be two records with the same age:

CREATE TABLE CUSTOMERS(
       ID   INT              NOT NULL,
       NAME VARCHAR (20)     NOT NULL,
       AGE  INT              NOT NULL UNIQUE,
       ADDRESS  CHAR (25) ,
       SALARY   DECIMAL (18, 2),       
       PRIMARY KEY (ID));

If the CUSTOMERS table has been created, then you want to add a unique constraint to the AGE column, similar to the following statement:

ALTER TABLE CUSTOMERS;
MODIFY AGE INT NOT NULL UNIQUE;

You can also use the following syntax, which supports named constraints on multiple columns:

ALTER TABLE CUSTOMERS;
ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);

Delete a unique constraint

To delete a UNIQUE constraint, Please use the following SQL:

ALTER TABLE CUSTOMERS;
DROP CONSTRAINT myUniqueConstraint;

If you are using MySQL, you can use the following syntax:

ALTER TABLE CUSTOMERS
DROP INDEX myUniqueConstraint;

The above is the detailed content of What is the use of sql unique constraint?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn