Home >Backend Development >PHP Tutorial >Related knowledge about SQL UNIQUE constraints

Related knowledge about SQL UNIQUE constraints

jacklove
jackloveOriginal
2018-05-08 10:41:371849browse

SQL UNIQUE Constraints are very important for php, this article explains them in detail.

SQL UNIQUE constraint

UNIQUE constraint uniquely identifies each record in a database table.

UNIQUE and PRIMARY KEY constraints both provide uniqueness guarantees for a column or set of columns.

PRIMARY KEY has automatically defined UNIQUE constraints.

Please note that each table can have multiple UNIQUE constraints, but each table can only have one PRIMARY KEY constraint.

SQL UNIQUE Constraint on CREATE TABLE

The following SQL creates a UNIQUE constraint in the "Id_P" column when the "Persons" table is created:

MySQL :

CREATE TABLE Persons
(
Id_P int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),UNIQUE (Id_P))

SQL Server / Oracle / MS Access:

CREATE TABLE Persons
(
Id_P int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

If you need to name UNIQUE constraints and define UNIQUE constraints for multiple columns, please use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons
(
Id_P int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),CONSTRAINT uc_PersonID UNIQUE (Id_P,LastName))

SQL UNIQUE Constraint on ALTER TABLE

When the table has been created, if you need to enter "Id_P" To create a UNIQUE constraint on a column, please use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE PersonsADD UNIQUE (Id_P)

If required To name a UNIQUE constraint, and to define UNIQUE constraints for multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE PersonsADD CONSTRAINT uc_PersonID UNIQUE (Id_P ,LastName)

Revoke UNIQUE constraint

To revoke UNIQUE constraint, please use the following SQL:

MySQL:

ALTER TABLE PersonsDROP INDEX uc_PersonID

This article explains the UNIQUE constraint. For more learning materials, please visit the php Chinese website.

Related recommendations:

Related knowledge about SQL NOT NULL constraints

How to use the SQL CREATE TABLE statement

Learn about the SQL INNER JOIN keyword

The above is the detailed content of Related knowledge about SQL UNIQUE constraints. 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