Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding NOT NULL column to SQLite table with references

Tags:

sql

sqlite

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?

like image 892
Dan Goodspeed Avatar asked Jul 02 '14 06:07

Dan Goodspeed


People also ask

Can we add a NOT NULL column to an existing table?

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.

How do you add a non NULL constraint to an existing column?

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.

How do I add a column to a table in SQLite?

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.


2 Answers

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;
like image 61
Googie Avatar answered Oct 03 '22 03:10

Googie


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.

like image 24
laalto Avatar answered Oct 03 '22 04:10

laalto