Skip to main content

How to Link Two Tables in SQLite with a Foreign Key

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

A book's author should be someone in the authors table, not a number that points nowhere. A foreign key makes SQLite check that link on every insert. This guide links books to their authors, with real output from SQLite 3.54.1.

Syntax​

Syntax
PRAGMA foreign_keys = ON;

CREATE TABLE <child table> (
<column> <type> REFERENCES <parent table> (<parent column>)
);
PartWhat it means
REFERENCES <parent table> (<parent column>)Every value in this column must exist in the parent table's column
<parent column>The parent table's primary key, or a column with a UNIQUE constraint
PRAGMA foreign_keys = ON;Turns the check on. SQLite leaves it off unless you ask, on every connection

SQLite's documentation on foreign keys: "SQL foreign key constraints are used to enforce "exists" relationships between tables."

Prerequisites​

  • The sqlite3 command-line shell. This guide uses SQLite 3.54.1. Run sqlite3 --version to see yours; the SQLite download page has the command-line tools for Windows, macOS and Linux.

Step 1: Write the Script​

Save this as foreign_key.sql:

foreign_key.sql
PRAGMA foreign_keys = ON;

CREATE TABLE authors (
author_id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);

CREATE TABLE books (
title TEXT NOT NULL,
author_id INTEGER NOT NULL REFERENCES authors (author_id)
);

INSERT INTO authors (author_id, name) VALUES (1, 'Jane Austen');
INSERT INTO books (title, author_id) VALUES ('Emma', 1);
INSERT INTO books (title, author_id) VALUES ('Dune', 2);

SELECT * FROM books;

The foreign_key.sql script in a macOS-style code window: PRAGMA foreign_keys = ON, an authors table, a books table whose author_id REFERENCES authors (author_id), Jane Austen as author 1, Emma inserted with author 1, Dune with author 2, and a SELECT of every book.

  • PRAGMA foreign_keys = ON; turns foreign key checks on. SQLite leaves them off unless you ask.
  • author_id ... REFERENCES authors (author_id) says each book's author_id must be an author_id in authors. authors is the parent table, and books is the child.
  • Jane Austen is author 1. Emma points at 1, which exists. Dune points at 2, which doesn't.

Step 2: Run It​

In the folder that holds the script, run:

Terminal
sqlite3 -table library.db ".read foreign_key.sql"

sqlite3 opens the database file library.db, and creates it when it isn't there. -table prints each result as a table, and .read runs the statements in the script. The command is the same in bash, zsh and PowerShell.

Output
Error near line 15 of foreign_key.sql: FOREIGN KEY constraint failed
+-------+-----------+
| title | author_id |
+-------+-----------+
| Emma | 1 |
+-------+-----------+

The output in a terminal: an error near line 15 of foreign_key.sql, FOREIGN KEY constraint failed, then the books table with one row, Emma with author_id 1.

Emma went in, because author 1 exists. Dune pointed at author 2, who isn't in authors, and SQLite refused it with FOREIGN KEY constraint failed. The message doesn't name the column, so look for the value that has no match in the parent table.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out PRAGMA foreign_keys = ONDune went in with author 2: without the pragma, SQLite doesn't checkTurn it on at the start of every connection
Pointing at a parent column that isn't its primary key or UNIQUEforeign key mismatch - "books" referencing "authors"Point at the primary key, or make the column UNIQUE

Troubleshooting​

SymptomLikely causeFix
FOREIGN KEY constraint failed on an INSERTThe value isn't in the parent tableInsert the parent row first, or fix the value
FOREIGN KEY constraint failed on a DELETERows in the child table still point at the parent rowDelete or change those rows first
no such table: main.authorsThe parent table doesn't exist yetCreate the parent table before inserting child rows
Parse error near line 3 of foreign_key.sql: table authors already existsThe script already ran on library.dbDelete library.db and run the script again

FAQ​

Can a book have no author?​

Yes, when the column allows NULL. With author_id INTEGER REFERENCES authors (author_id), without NOT NULL, a book with a NULL author went in. SQLite only checks the values that are there.

Why does SQLite leave foreign keys off?​

For older programs. The documentation: "Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection."

Conclusion​

REFERENCES authors (author_id), with PRAGMA foreign_keys = ON, let Emma in with author 1 and refused Dune, whose author 2 doesn't exist.

Additional Resources​