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
MySQLYou can click on above box to edit the code and run again.
CREATE TABLE student(
id int NOT NULL , Last_name varchar( 50 ) NOT NULL , First_name varchar( 50 ) , Age int, PRIMARY KEY (id) );
Output
Example
SQL Server / Oracle / MS Access:You can click on above box to edit the code and run again.
CREATE TABLE student( id int NOT NULL PRIMARY KEY , Last_name varchar( 50 ) NOT NULL , First_name varchar( 50 ) , Age int, );
Output
Example
MySQL / SQL Server / Oracle / MS Access:You can click on above box to edit the code and run again.
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) );
Output
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:You can click on above box to edit the code and run again.
ALTER TABLE student ADD PRIMARY KEY (id);
Output
Example
MySQL / SQL Server / Oracle / MS Access:You can click on above box to edit the code and run again.
ALTER TABLE student ADD CONSTRAINT PK_student PRIMARY KEY (id,Last_name);
Output
DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
Example
MySQLYou can click on above box to edit the code and run again.
ALTER TABLE student DROP PRIMARY KEY;