Constraints and Indexes
Primary Key
Stable Row Identity
A primary key identifies rows. It is the column other tables often reference.
Program
Play the script to create stable user IDs.
primary_key.sql
Replay: real traced execution (multi-file project)
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO users VALUES (1, 'Ada'), (2, 'Lin');
SELECT id, name FROM users ORDER BY id;
tables ← 1 row
1CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);2INSERT INTO users VALUES (1, 'Ada'), (2, 'Lin');values this step1 rowtablesusers ← 2 rows
1CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);2INSERT INTO users VALUES (1, 'Ada'), (2, 'Lin');3SELECT id, name FROM users ORDER BY id;values this step2 rowsusersresult ← 2 rows
2INSERT INTO users VALUES (1, 'Ada'), (2, 'Lin');3SELECT id, name FROM users ORDER BY id;values this step2 rowsresult
Follow the Rows
usershasid INTEGER PRIMARY KEYandname.- The script inserts id
1with nameAda. - It also inserts id
2with nameLin. ORDER BY idkeeps1before2.- The final rows are
1 Adaand2 Lin. | id | name | | --- | --- | | 1 | Ada | | 2 | Lin |
PRIMARY KEY
`PRIMARY KEY` marks a row identifier.
identity
IDs make rows easy to reference from other tables.
ordering
Primary keys are often used for stable output order.
Exercise: primary_key.sql
Reproduce the rows 1 Ada and 2 Lin, then identify which column gives each row its stable id.