SQL PRIMARY KEY Constraint
ThePRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).
SQL PRIMARY KEY on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "ID" column when the "student" table is created:
Example
MySQL
CREATE TABLE student(
id int NOT NULL ,
Last_name varchar( 50 ) NOT NULL ,
First_name varchar( 50 ) ,
Age int,
PRIMARY KEY (id)
);
Example
SQL Server / Oracle / MS Access:
CREATE TABLE student(
id int NOT NULL PRIMARY KEY ,
Last_name varchar( 50 ) NOT NULL ,
First_name varchar( 50 ) ,
Age int,
);
Example
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE student(
id int NOT NULL ,
Last_name varchar( 50 ) NOT NULL ,
First_name varchar( 50 ) ,
Age int,
CONSTRAINT PK_student PRIMARY KEY(id, Last_name)
);
SQL PRIMARY KEY on ALTER TABLE
The following SQL creates a PRIMARY KEY constraint on the "id" column when the table is already created, use the following SQL:
Example
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE student
ADD PRIMARY KEY (id);
Example
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE student
ADD CONSTRAINT PK_student PRIMARY KEY (id,Last_name);