Before continuing: This entry is part of the constraints and keys guide. If you are new to the topic, start with CREATE TABLE.
PRIMARY KEY example
CREATE TABLE customers_demo (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);When the key uses a single column, it can be declared next to the column definition.
CREATE TABLE enrollments_demo (
course_id INTEGER NOT NULL,
student_id INTEGER NOT NULL,
date TEXT NOT NULL,
PRIMARY KEY (course_id, student_id)
);The second table prevents the same pair from appearing twice course_id–student_id, but still lets a course have many students and a student take several courses.
How PRIMARY KEY is used
When the key uses a single column, it can be declared next to the column definition.
The second table prevents the same pair from appearing twice course_id–student_id, but still lets a course have many students and a student take several courses.
Common mix-ups with PRIMARY KEY
Choosing a value that changes as the identifier
Using a name, phone number or address as a key tends to cause problems when the value changes or is not truly unique. You should also avoid generating identifiers with MAX(id) + 1: two operations running at the same time could compute the same value.
INSERT INTO customers_demo (id, name)
VALUES (1, 'Megan');This insert fails because the value 1 already identifies Amy.
Key differences between engines
The constraint itself is common to the major engines. What differs is how values are generated automatically: identity columns, sequences, AUTO_INCREMENT and the special behaviour of INTEGER PRIMARY KEY in SQLite are not one portable syntax.
SQLite keeps a historical exception: a primary key that is not an INTEGER PRIMARY KEY can accept NULL if the table is neither STRICT nor WITHOUT ROWID and the column is not declared NOT NULL. That is why the composite key examples declare every column as NOT NULL explicitly. Define the identity rule first, then adapt both the constraint and the value generation to your engine.