Tutorial on SQL UNIQUE constraints

Source: Internet
Author: User

SQL statements with unique constraints
The unique constraint uniquely identifies each record in a database table.

Both the uniqueness and primary constraints provide a unique column or a group of columns.

A primary key constraint automatically defines it with a unique constraint.

Note that you can have many unique restrictions on each table, but only one primary key constraint per seat.


Unique SQL constraints for creating tables
When the following SQL statement creates a column named "P_Id" with a unique constraint, "person" creates a table:

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

SQL Server/Oracle/MS Access:

 

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

To name a unique constraint and determine the unique constraint on multiple columns, use the following SQL Syntax:

For MySQL/SQL Server/Oracle/MS Access:

 

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

Unique constraints of Database Change table
To create a column named "P_Id" with a unique constraint, the table has been created. Use the following SQL statement:

ALTER TABLE PersonsADD UNIQUE (P_Id)
 

To name a unique constraint and determine the unique constraint on multiple columns, use the following SQL Syntax:

 

ALTER TABLE PersonsADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
 

Drop unique is a unique constraint
To discard a unique constraint, use the following SQL:

 

ALTER TABLE PersonsDROP INDEX uc_PersonID
 

SQL Server / Oracle / MS Access:

ALTER TABLE PersonsDROP CONSTRAINT uc_PersonID

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.