PRIMARY KEY

Overview

The PRIMARY KEY constraint uniquely identifies each row in a table. A primary key must be unique and cannot contain NULL values. A table can have only one primary key.

Primary keys are essential for relational databases as they ensure entity integrity and enable relationships between tables through foreign keys.

Basic Syntax

PRIMARY KEY Syntax
-- In CREATE TABLE
CREATE TABLE table_name (
    column_name datatype PRIMARY KEY,
    ...
);

-- Or at table level
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    PRIMARY KEY (column1)
);

Examples

Example 1: Single Column Primary Key

Column-level primary key
CREATE TABLE Customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100)
);

Example 2: Table-Level Primary Key

Table-level primary key
CREATE TABLE Customers (
    customer_id INT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100),
    PRIMARY KEY (customer_id)
);

Example 3: Composite Primary Key

Multiple columns as primary key
CREATE TABLE OrderItems (
    order_id INT NOT NULL,
    product_id INT NOT NULL,
    quantity INT,
    PRIMARY KEY (order_id, product_id)
);

Example 4: Primary Key with AUTO_INCREMENT

Auto-incrementing primary key
-- MySQL
CREATE TABLE Customers (
    customer_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100)
);

-- SQL Server
CREATE TABLE Customers (
    customer_id INT PRIMARY KEY IDENTITY(1,1),
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100)
);

-- PostgreSQL
CREATE TABLE Customers (
    customer_id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100)
);

Properties of Primary Key

A primary key must satisfy these properties:

Adding Primary Key to Existing Table

You can add a primary key using ALTER TABLE:

Add primary key later
-- First, ensure column is NOT NULL
ALTER TABLE Customers
MODIFY COLUMN customer_id INT NOT NULL;

-- Then add primary key
ALTER TABLE Customers
ADD PRIMARY KEY (customer_id);

Dropping Primary Key

You can remove a primary key constraint:

Remove primary key
ALTER TABLE Customers
DROP PRIMARY KEY;

Primary Key vs Unique

Understanding the difference:

Property PRIMARY KEY UNIQUE
NULL values Not allowed One NULL allowed (varies)
Count per table One Multiple
Index Creates clustered index Creates non-clustered index
Purpose Row identifier Prevent duplicates

Best Practices

Common Mistakes

Next Steps

Learn about linking tables with FOREIGN KEY, or explore other constraints in Constraints.