THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

SQL PRIMARY KEY Constraint


SQL PRIMARY KEY Constraint

The PRIMARY KEY imperative interestingly distinguishes each record in a database table.

Primary keys must contain UNIQUE values.

A essential key section can't contain NULL values.

Most tables ought to have an essential key, and each table can have just a single essential key.


SQL PRIMARY KEY Constraint on CREATE TABLE

The following SQL makes a PRIMARY KEY on the "User_Id" section when the "Persons" table is created:

MySQL:

Make TABLE Persons
(
User_Id int NOT NULL,
Username varchar(255) NOT NULL,
Secret word varchar(255),
Email varchar(255),
Telephone varchar(255),
Essential KEY (User_Id)
)

SQL Server/Oracle/MS Access:

Make TABLE Persons
(
User_Id int NOT NULL PRIMARY KEY,
Username varchar(255) NOT NULL,
Secret word varchar(255),
Email varchar(255),
Telephone varchar(255)
)

To permit naming of a PRIMARY KEY requirement, and for characterizing a PRIMARY KEY imperative on different segments, utilize the accompanying SQL syntax:

MySQL/SQL Server/Oracle/MS Access:

Make TABLE Persons
(
User_Id int NOT NULL,
Username varchar(255) NOT NULL,
Secret phrase varchar(255),
Email varchar(255),
Telephone varchar(255),
Limitation pk_PersonID PRIMARY KEY (User_Id,Username)
)

Note: In the model above there is just a single PRIMARY KEY (pk_PersonID). In any case, the VALUE of the essential key is comprised of TWO COLUMNS (User_Id + Username).


SQL PRIMARY KEY Constraint on ALTER TABLE

To make a PRIMARY KEY limitation on the "User_Id" segment when the table is now made, utilize the accompanying SQL:

MySQL/SQL Server/Oracle/MS Access:

Modify TABLE Persons
Include PRIMARY KEY (User_Id)

To permit naming of a PRIMARY KEY limitation, and for characterizing a PRIMARY KEY imperative on numerous sections, utilize the accompanying SQL syntax:

MySQL/SQL Server/Oracle/MS Access:

Modify TABLE Persons
Include CONSTRAINT pk_PersonID PRIMARY KEY (User_Id,Username)

Note: If you utilize the ALTER TABLE proclamation to include an essential key, the essential key column(s) must as of now have been proclaimed to not contain NULL qualities (when the table was first created).


To DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY requirement, utilize the accompanying SQL:

MySQL:

Modify TABLE Persons
DROP PRIMARY KEY

SQL Server/Oracle/MS Access:

Modify TABLE Persons
DROP CONSTRAINT pk_PersonID