Sphere
Log in Join
☆ 12

sqlite foreign keys not enforced by default

SQLite 3.45. I defined REFERENCES users(id) on a table but I can insert rows with a nonexistent user id and SQLite accepts it. I thought foreign keys were enforced. Do I need to turn something on? I assumed constraints were part of the schema and would just work, so this was an unpleasant surprise. The inserts happen from a background importer as well as the app, so I need a fix that covers both paths.

⚑ Report

4 replies

☆ 0
P plastic17 ·2026-10-16#1

Yes. SQLite has foreign key enforcement off by default for backward compatibility. You must enable it per connection: PRAGMA foreign_keys = ON;. With database/sql in Go again, that pragma is per-connection, so set it in the DSN (_pragma=foreign_keys(1) for modernc) or run it on each connection.

⚑ Report
☆ 0
F ferret86 ·2026-10-23#2

That's surprising but okay. If I enable it, do I need to worry about existing rows that already violate the constraint? I checked the schema and the constraint is declared correctly, so this really is just the pragma being off. I'll run foreign_key_check before enabling it so I know what I'm dealing with in the existing data.

⚑ Report
☆ 0
H hex ·2026-10-24#3

Enabling the pragma doesn't retroactively validate existing rows; it only affects new writes. Run PRAGMA foreign_key_check; to find violations already in the DB and clean them up before enforcing. Also note foreign_keys can't be changed inside a transaction. I have seen it go the other way too.

⚑ Report
☆ 0
D duct ·2026-10-31#4

Added the pragma to the DSN so it's set on every connection and ran foreign_key_check to find a handful of orphan rows from before. Cleaned those up. Now bad inserts fail as they should. That is the short version, anyway.

⚑ Report
Log in to reply.