SQLite PRIMARY KEY Constraint
PRIMARY KEY
A primary key uniquely identifies each record in a table. A table can have only one primary key.
Example
CREATE TABLE IF NOT EXISTS Persons (
PersonID INTEGER PRIMARY KEY,
LastName TEXT NOT NULL,
FirstName TEXT
);
Try it Yourself »
INTEGER PRIMARY KEY
A column of the type INTEGER PRIMARY KEY is special in SQLite. If you insert a record without a value for it, SQLite gives the record the next number automatically:
Example
CREATE TABLE IF NOT EXISTS Persons (
PersonID INTEGER PRIMARY KEY,
LastName TEXT NOT NULL,
FirstName TEXT
);
INSERT INTO Persons (LastName, FirstName)
VALUES ('Hansen', 'Emil'), ('Berg', 'Nora');
SELECT * FROM Persons;
Try it Yourself »
All the Northwind tables use INTEGER PRIMARY KEY for their id columns.
The rowid
Every normal SQLite table has a hidden column named rowid, with a unique number for each record. An INTEGER PRIMARY KEY column is just another name for the rowid:
Primary Key on More Than One Column
A primary key can be a combination of columns. Then it is written as a table constraint:
Example
CREATE TABLE IF NOT EXISTS OrderLines (
OrderID INTEGER,
LineNumber INTEGER,
ProductID INTEGER,
PRIMARY KEY (OrderID, LineNumber)
);
Try it Yourself »
Note: Because of an old bug that is kept for compatibility, SQLite allows NULL in a primary key column that is not an INTEGER PRIMARY KEY. Add NOT NULL to be sure.