Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3 "foreign key constraint failed"

Tags:

I've set up two tables:

CREATE TABLE A (     id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,     name TEXT  );  CREATE TABLE B (     id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,     id2 INTEGER,     book TEXT,     FOREIGN KEY(id2) REFERENCES A(id) ); 

After I insert data into A, it looks like this:

1    John  2    Amy  3    Peter 

After I insert data into B, it looks like this:

1     1     Lord of the Rings  2     1     Catch 22  3     2     Sum of All Fears  4     3     Hunt for Red October 

I then execute the following statement:

delete from a where id=1; 

I get the following: "Error: foreign key constraint failed"

I then restart sqlite3 and try again but this time I enter this first:

PRAGMA foreign_keys = 1; 

it still doesn't work......

like image 852
A B Avatar asked Mar 15 '13 23:03

A B


People also ask

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.

Does sqlite3 support foreign keys?

SQLite foreign key constraint supportSQLite has supported foreign key constraint since version 3.6.

How do I reference a foreign key in SQLite?

How to Add a Foreign Key to an Existing Table. You can not use the ALTER TABLE statement to add a foreign key in SQLite. Instead you will need to rename the table, create a new table with the foreign key, and then copy the data into the new table.


2 Answers

Table B has rows whose foreign key references the primary key value of the Table A row you are trying to delete so deleting it would violate the integrity of your database.

You could include ON DELETE CASCADE in your foreign key definition. With that, when you delete an entry from Table A, any entries in Table B linked to the deleted row would also be deleted. Don't know if that's appropriate for your application.

like image 93
phaworth Avatar answered Oct 21 '22 13:10

phaworth


The "problem" is that you have set a foreign key on table B.

foreign key(id2) references A(id) 

This means that column id2 in table B references column id in table A. Both Lord of the Rings and Catch 22 from Table B are linked to John from Table A. Therefore you cannot delete John without first deleting these other two entries from Table B first.

The alternative would be to remove the foreign key.

See this documentation for more details.

like image 31
Kyle Avatar answered Oct 21 '22 13:10

Kyle