Easy Tutorial
❮ Sql Func Round Sql Func First ❯

SQL PRIMARY KEY Constraint


SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table.

The primary key must contain unique values.

The primary key column cannot contain NULL values.

Every table should have a primary key, and each table can have only one primary key.


SQL PRIMARY KEY Constraint When Creating a Table

The following SQL creates a PRIMARY KEY constraint on the "P_Id" column when the "Persons" table is created:

MySQL:

SQL Server / Oracle / MS Access:

To name a PRIMARY KEY constraint and define a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

Note: In the above example, there is only one primary key PRIMARY KEY (pk_PersonID). However, the value of pk_PersonID is composed of two columns (P_Id and LastName).


SQL PRIMARY KEY Constraint When Altering a Table

To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

To name a PRIMARY KEY constraint and define a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

Note: If you use the ALTER TABLE statement to add a primary key, you must declare the primary key column to not contain NULL values (when the table was first created).


Drop PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

MySQL:

SQL Server / Oracle / MS Access:

❮ Sql Func Round Sql Func First ❯