Keys and relationship shapes

Lesson 13 of 18 · SQL foundations

A primary key identifies a row; a foreign key references a parent key. One shelf can hold many books; each book in this schema points to at most one shelf. A one-to-one relationship can be enforced with a unique foreign key, though this does not automatically require every parent to have a child. For many-to-many relationships, use an association table.

shelves 1 ───── 0..many books
books   1 ───── 0..many book_topics  many..0 ───── 1 topics

For example, a book may have many topics and a topic may describe many books:

CREATE TABLE topics (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE);
CREATE TABLE book_topics (
  book_id INTEGER NOT NULL REFERENCES books(id),
  topic_id INTEGER NOT NULL REFERENCES topics(id),
  PRIMARY KEY (book_id, topic_id)
);

The composite key prevents a repeated pair; each foreign key checks one endpoint. The association table may also hold facts about the relationship, such as when a topic was assigned. Enforcement requires PRAGMA foreign_keys = ON on each SQLite connection.

Chapter index · Course index