HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

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) );
You can click on above box to edit the code and run again.

Output

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, );
You can click on above box to edit the code and run again.

Output

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

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) );
You can click on above box to edit the code and run again.

Output

Note: In the example above there is only ONE PRIMARY KEY (PK_student). However, the VALUE of the primary key is made up of TWO COLUMNS (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);
You can click on above box to edit the code and run again.

Output

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

Example

MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE student ADD CONSTRAINT PK_student PRIMARY KEY (id,Last_name);
You can click on above box to edit the code and run again.

Output

NOTE: If you use ALTER TABLE to add a primary key, the primary key column(s) must have been declared to not contain NULL values (when the table was first created).

DROP a PRIMARY KEY Constraint


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

Example

MySQL 
ALTER TABLE student DROP PRIMARY KEY;
You can click on above box to edit the code and run again.

Output

Example

 SQL Server / Oracle / MS Access:
ALTER TABLE student DROP CONSTRAINT PK_student;
You can click on above box to edit the code and run again.

Output