0

If I enable foreign key validation I cannot insert proper values, which fit with my foreign key definition. What am I missing here?

$ sqlite3 test.db
sqlite> CREATE TABLE a (id INTEGER NOT NULL, item TEXT NOT NULL);
sqlite> CREATE TABLE b (id INTEGER NOT NULL, item TEXT NOT NULL,
                        ref INTEGER REFERENCES a (id));
sqlite> INSERT INTO a VALUES (16, 'test');
sqlite> PRAGMA foreign_keys = 1;
sqlite> INSERT INTO b VALUES (16, 'test2', 16);
Error: foreign key mismatch - "b" referencing "a"
sqlite> SELECT * FROM a;
16|test
Googie
  • 5,742
  • 2
  • 19
  • 31

1 Answers1

1

I googled and found this answer to a previous question, that cites the documentation:

Usually, the parent key of a foreign key constraint is the primary key of the parent table. If they are not the primary key, then the parent key columns must be collectively subject to a UNIQUE constraint or have a UNIQUE index.

When you add a UNIQUE constraint to your a.id column, the example works:

$ sqlite3
sqlite> CREATE TABLE a (id INTEGER UNIQUE NOT NULL, item TEXT NOT NULL);
sqlite> CREATE TABLE b (id INTEGER NOT NULL, item TEXT NOT NULL,
   ...>   ref INTEGER REFERENCES a(id));
sqlite> INSERT INTO a VALUES (16, 'test');
sqlite> INSERT INTO b VALUES (16, 'test2', 16);
sqlite> SELECT * FROM a;
16|test
sqlite> SELECT * FROM b;
16|test2|16
Community
  • 1
  • 1
Frxstrem
  • 38,761
  • 9
  • 79
  • 119