PRIMARY KEY

The primary key is an attribute that is assigned to a column to ensure it contains unique values.
The primary key serves to uniquely identify each row in the table.
A table can only have one primary key; however, it can include more than one attribute (called a composite or concatenated primary key).
The primary key is a column in a table that uniquely identifiers every record in that table.
This means that no two cells within the primary column can be the same.


The absence of a primary key in a table means that the data in that table is harder to access and subsequently slower in operation.


Internally, the designation of a primary key will automatically create a primary key index
A primary key is required on a table if you want to apply any Referential Integrity constraints


When you apply a primary key constraint to a column you are also indirectly also applying a NOT NULL constraint



Applying On Creation


CREATE TABLE MyProducts 
(
ProductID INTEGER CONSTRAINT constraint_name PRIMARY KEY
)
or
CREATE TABLE MyProducts
(
ProductID INTEGER

CONSTRAINT constraint_name PRIMARY KEY (ProductID)
)


Applying After Creation

You cannot add this constraint to a column that already contains null values


ALTER TABLE MyProducts 
ADD CONSTRAINT constraint_name PRIMARY KEY (ProductID)

Multiple Columns

Sometimes it is necessary to include more than one column in your primary key
It is possible to create concatenated prrimary keys


applying on creation

CREATE TABLE MyProducts 
(
ProductID INTEGER
AnotherID INTEGER

CONSTRAINT constraint_name PRIMARY KEY (ProductID, AnotherID)
)

or
apply after creation

CREATE TABLE MyProducts 
(
ProductID INTEGER NOT NULL
AnotherID INTEGER NOT NULL
)

ALTER TABLE MyProducts
ADD CONSTRAINT constraint_name PRIMARY KEY (ProductID, AnotherID)


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext