PRIMARY KEY Constraint
PRIMARY KEY Constraint
PRIMARY KEYS serve as distinct identifiers for each row in a table. They can be values found in a table's single column or a combination of the table's several columns. The PRIMARY KEY column needs to be UNIQUE and cannot be NULL. The primary key in the table's value is a unique identifier for a specific row in the parent table that links the row to additional information present in the child table, where the same distinct identity also exists as a FOREIGN KEY. The PRIMARY KEY constraint can be set either when the table is created or at a later time using an alter statement.
The following query creates a PRIMARY KEY on the Customer_Id column in the Customer table.
sql
CREATE TABLE Customer (
Customer_Id int NOT NULL UNIQUE,
Age int,
City varchar(255) DEFAULT ‘Unknown City’,
CHECK (Age>18)
);
If we’d like to add a PRIMARY KEY after the creation of the table, we’d have to run the following ALTER statement:
ALTER TABLE Customer (
ADD PRIMARY KEY (Customer_Id);
);


The Customer_Id is the PRIMARY KEY in the Customer Table. However, the Customer_Id is a FOREIGN KEY in the Orders Table.
In order to create the Orders table, we run the following SQL query: