I have the following table:
CREATE TABLE child(
id INTEGER PRIMARY KEY,
parent_id INTEGER,
description TEXT);
How do I add a foreign key constraint on parent_id
? Assume foreign keys are enabled.
Most examples assume you're creating the table - I'd like to add the constraint to an existing one.
You can try this:
Please check https://www.sqlite.org/lang_altertable.html#otheralter
Basically you cannot but you can bypass the situation.
The correct way to add the foreign key constraint to an existing table is the following command.
Then copy the parent_Id data to the newCol and then delete the Parent_Id column. Hence, no need for temporary table.
You can't.
Although the SQL-92 syntax to add a foreign key to your table would be as follows:
SQLite doesn't support the
ADD CONSTRAINT
variant of theALTER TABLE
command (sqlite.org: SQL Features That SQLite Does Not Implement).Therefore, the only way to add a foreign key in sqlite 3.6.1 is during
CREATE TABLE
as follows:Unfortunately you will have to save the existing data to a temporary table, drop the old table, create the new table with the FK constraint, then copy the data back in from the temporary table. (sqlite.org - FAQ: Q11)
Yes, you can, without adding a new column. You have to be careful to do it correctly in order to avoid corrupting the database, so you should completely back up your database before trying this.
for your specific example:
or more generally:
Either way, you'll probably want to first see what the SQL definition is before you make any changes:
If you use the replace() approach, you may find it helpful, before executing, to first test your replace() command by running:
First add a column in child table
Cid
asint
thenalter table
with the code below. This way you can add the foreign keyCid
as the primary key of parent table and use it as the foreign key in child table ... hope it will help you as it is good for me: