How to add a foreign key relationship in sqlite How to add a foreign key relationship in sqlite sqlite sqlite

How to add a foreign key relationship in sqlite


You have to enable foreign keys support:

PRAGMA foreign_keys=ON;

Reference: http://www.sqlite.org/foreignkeys.html

Example:

sqlite> create table A(   ...>     id integer primary key autoincrement,   ...>     subject text not null   ...> );sqlite> sqlite> create table B(   ...>     id integer primary key autoincrement,   ...>     text integer references A(id)   ...>         on delete restrict   ...>         deferrable initially deferred   ...>         unique   ...> );sqlite> insert into a values(1,1),(2,2);sqlite> insert into b(text) values(3);sqlite> pragma foreign_keys=on;sqlite> insert into b(text) values(4);Error: foreign key constraint failedsqlite>