Primary Key in SQL

The PRIMARY KEY uniquely identifies each record in a database table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only one primary key, which may consist of single or multiple fields.

images/articles/mysql/primary-key-in-sql.jpg

For example, the following SQL creates a PRIMARY KEY on the "id" column when the "Persons" table is created.

CREATE TABLE Persons (
id INT NOT NULL,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Age INT,
PRIMARY KEY (id)
);

To create a PRIMARY KEY on the "id" column when the table is already created,

ALTER TABLE Persons
ADD PRIMARY KEY (id);

To drop a PRIMARY KEY,

ALTER TABLE Persons
DROP PRIMARY KEY;