Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional SQLite check constraint?

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.

like image 896
Rezzie Avatar asked Apr 10 '10 23:04

Rezzie


People also ask

Does SQLite support check constraints?

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.

What are SQLite constraints?

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.

How do I delete a constraint in SQLite?

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.


2 Answers

How about:

CHECK (status = "Current" or (status = "Complete" and enddate is not null)) 
like image 56
Andomar Avatar answered Oct 16 '22 09:10

Andomar


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.

like image 40
Ensarija Avatar answered Oct 16 '22 09:10

Ensarija