SQL Learning
SQL PRIMARY KEY Constraint
SQL Learning
SQL PRIMARY KEY Constraint
Learn how PRIMARY KEY ensures each row in your table is uniquely identifiable. Essential for relational database design.
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 KEY
s
Tips for Using PRIMARY KEYs
- Use an
INTEGER
primary key for simplicity and performance - Avoid using
email
orusername
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