SQL
SQL Primary Key

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table.

  • Primary keys must contain UNIQUE values.
  • Primary keys cannot contain NULL values.
  • A table can have only ONE primary key.
  • A primary key can consist of a single column or multiple columns.

SQL PRIMARY KEY on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:

MySQL:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    PRIMARY KEY (ID)
);

Key Characteristics of a Primary Key:

  • Uniqueness: Every value in the primary key column(s) must be unique.
  • No NULLs: A primary key column cannot have NULL values.
  • One per table: Each table can have only one primary key.
  • Can be composite: A primary key can be made up of one or more columns (called a composite key).

Why Use a Primary Key?

To make sure that each row in a table can be uniquely and reliably identified — which is critical for data integrity, relationships (via foreign keys), and performance.