I have a table defined by the following SQL:
CREATE TABLE test ( id integer PRIMARY KEY NOT NULL UNIQUE, status text NOT NULL, enddate date, /* Checks */ CHECK (status IN ("Current", "Complete")) );
I'd like to add a constraint that requires enddate
to be non-null if the status
is "Complete".
Is this possible? I am using SQLite v3.6.16.
SQLite allows you to define a CHECK constraint at the column level or the table level. In this syntax, whenever a row is inserted into a table or an existing row is updated, the expression associated with each CHECK constraint is evaluated and returned a numeric value 0 or 1.
Constraints are the rules enforced on a data columns on table. These are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the database. Constraints could be column level or table level.
SQLite does not (as of this answer) support the alter table drop constraint command. The allowed syntax can be seen here. You will need to create a new table without a constraint, transfer the data, then delete the old table.
How about:
CHECK (status = "Current" or (status = "Complete" and enddate is not null))
CREATE TABLE test ( id integer PRIMARY KEY, status text NOT NULL CHECK (status IN ('Current', 'Complete')), enddate date NOT NULL );
This will work in SQLite, with the CHECK
constraint written inline. I changed double quotes to apostrophes so it can be used in PHP.
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