I need to add a column to my existing SQLite table that references a column in another table. I use the command
ALTER TABLE users
ADD COLUMN dayChoice_id INTEGER
NOT NULL REFERENCES dayChoice(dayChoice_id) DEFAULT 0
And I get the error "Cannot add a REFERENCES column with non-NULL default value". Is that true? How would I add the column then?
You can add a not null column at the time of table creation or you can use it for an existing table. In the above table, we have declared Id as int type that does not take NULL value. If you insert NULL value, you will get an error.
To enforce NOT NULL for a column in SQL Server, use the ALTER TABLE .. ALTER COLUMN command and restate the column definition, adding the NOT NULL attribute.
Use ALTER TABLE table_name ADD COLUMN column_definition statement to add a column to a table. Use ALTER TABLE table_name RENAME COLUMN current_name TO new_name to rename a column.
You need to disable foreign keys enforcing for the time of executing this ALTER
statement, like this:
PRAGMA foreign_keys = 0;
ALTER TABLE users ADD COLUMN dayChoice_id INTEGER
NOT NULL REFERENCES dayChoice(dayChoice_id) DEFAULT 0;
PRAGMA foreign_keys = 1;
From the docs:
If foreign key constraints are enabled and a column with a REFERENCES clause is added, the column must have a default value of NULL.
The default value you supplied was not NULL.
It's not compatible with another requirement:
If a NOT NULL constraint is specified, then the column must have a default value other than NULL.
You can probably work around the problem by temporarily disabling foreign key constraints before the ALTER TABLE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With