LogoInterview Master

SQL Learning

SQL PRIMARY KEY Constraint

What Is a PRIMARY KEY in SQL?

A PRIMARY KEY is a column—or a combination of columns—that uniquely identifies each row in a table. It prevents duplicate values and ensures every row can be referenced reliably.

Key Properties

  • Must be unique across all rows
  • Cannot contain NULL values
  • Each table can have only one PRIMARY KEY

Defining a PRIMARY KEY

Inline Definition

CREATE TABLE Users (
  user_id INTEGER PRIMARY KEY,
  username TEXT NOT NULL
);

Table-Level Definition

CREATE TABLE Videos (
  video_id INTEGER,
  title TEXT,
  upload_date DATE,
  PRIMARY KEY (video_id)
);

Composite Primary Key

Use more than one column to uniquely identify rows.

CREATE TABLE Interactions (
  user_id INTEGER,
  video_id INTEGER,
  interaction_type TEXT,
  PRIMARY KEY (user_id, video_id)
);

Why PRIMARY KEYs Matter

  • They enable fast lookups and indexing
  • They enforce data integrity—no duplicates allowed
  • They support relationships via FOREIGN KEYs

Tips for Using PRIMARY KEYs

  • Use an INTEGER primary key for simplicity and performance
  • Avoid using email or username as a primary key—they can change!
  • Use a surrogate key (like id) and keep natural keys as unique constraints
  • Index your foreign key columns for faster joins

Loading SQL editor...