Skip to main content

How to Turn On Foreign Keys in SQLite with PRAGMA foreign_keys

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

SQLite checks foreign keys only when you ask it to, and the setting lasts for one connection. Until then, a book can point at an author who doesn't exist. This guide shows the setting off, turns it on with PRAGMA foreign_keys, and finds it off again in the next connection, with real output from SQLite 3.54.1.

Syntax​

Syntax
PRAGMA foreign_keys = ON;
PRAGMA foreign_keys;
PartWhat it means
PRAGMA foreign_keys = ON;Turns foreign key checks on for this connection. OFF turns them off
PRAGMA foreign_keys;Shows the setting: 1 when checks are on, 0 when they're off

A pragma is a SQLite command that reads or changes a setting. SQLite's documentation on foreign keys: "Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection."

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_keys_on.sql:

foreign_keys_on.sql
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)
);

PRAGMA foreign_keys;
INSERT INTO books (title, author_id) VALUES ('Dune', 7);

PRAGMA foreign_keys = ON;
PRAGMA foreign_keys;
INSERT INTO books (title, author_id) VALUES ('Emma', 7);

SELECT * FROM books;

The foreign_keys_on.sql script in a macOS-style code window: an authors table, a books table whose author_id references authors, PRAGMA foreign_keys to show the setting, an insert of Dune with author 7, PRAGMA foreign_keys = ON, the setting shown again, an insert of Emma with author 7, and a SELECT of every book.

  • The first PRAGMA foreign_keys; shows the setting before anything changes it.
  • Dune points at author 7, who doesn't exist. The authors table is empty.
  • PRAGMA foreign_keys = ON; turns checks on, and the second PRAGMA foreign_keys; shows the new setting.
  • Emma points at the same missing author 7, now with checks on.

Step 2: Run It​

In the folder that holds the script, run:

Terminal
sqlite3 -table library.db ".read foreign_keys_on.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
+--------------+
| foreign_keys |
+--------------+
| 0 |
+--------------+
+--------------+
| foreign_keys |
+--------------+
| 1 |
+--------------+
Error near line 16 of foreign_keys_on.sql: FOREIGN KEY constraint failed
+-------+-----------+
| title | author_id |
+-------+-----------+
| Dune | 7 |
+-------+-----------+

The setting started at 0, so Dune went in with an author who doesn't exist. After = ON it showed 1, and Emma, with the same missing author, was refused at line 16. Dune is still in the table: turning checks on doesn't look at rows that are already there.

Step 3: Check the Next Connection​

Each sqlite3 command opens its own connection to the database. Ask the setting again:

Terminal
sqlite3 -table library.db "PRAGMA foreign_keys;"
Output
+--------------+
| foreign_keys |
+--------------+
| 0 |
+--------------+

Both runs in a terminal: the script's output with foreign_keys 0, then 1, an error near line 16, FOREIGN KEY constraint failed, and the books table with Dune at author 7, then a new sqlite3 command whose PRAGMA foreign_keys shows 0.

Back to 0. The setting lives in the connection, not in library.db, so every connection has to turn it on again.

Common Mistakes​

MistakeWhat happensDo this instead
Turning it on after BEGINThe setting stayed 0. The documentation: "This pragma is a no-op within a transaction"Run it before BEGIN
A typo, such as PRAGMA foreign_key = ONNo error, and checks stayed off: "No error messages are generated if an unknown pragma is issued."Check with PRAGMA foreign_keys;

Troubleshooting​

SymptomLikely causeFix
A row with a missing parent went inChecks were off for that connectionRun PRAGMA foreign_keys = ON; first, in every connection
FOREIGN KEY constraint failedThe value isn't in the parent tableInsert the parent row first, or fix the value
Parse error near line 1 of foreign_keys_on.sql: table authors already existsThe script already ran on library.dbDelete library.db and run the script again

FAQ​

How do I find rows that already break a foreign key?​

With PRAGMA foreign_key_check;. On this database it returned one row, books | 1 | authors | 0: the table, the bad row's rowid, the parent table, and the number of the foreign key it breaks. The documentation: "The foreign_key_check pragma returns one row output for each foreign key violation."

Does the setting stay on?​

Only for the connection that set it. Step 3 opened a new one, and the setting was 0 again.

Conclusion​

PRAGMA foreign_keys = ON; changed the setting from 0 to 1 and made SQLite refuse Emma's missing author. The next connection started at 0 again.

Additional Resources​