Conditional SQLite check constraint?

2019-02-05 14:08发布

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.

3条回答
2楼-- · 2019-02-05 15:02
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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-05 15:02

There's nothing stopping you from having multiple CHECK constraints on a single table. IMO the simplest and most easily expandable solution:

CHECK (status IN ("Current", "Complete"))
CHECK (status <> "Complete" OR enddate IS NOT NULL)

This uses the fact that if A then B is logically equivalent to either not A or B.

查看更多
唯我独甜
4楼-- · 2019-02-05 15:06

How about:

CHECK (status = "Current" or (status = "Complete" and enddate is not null))
查看更多
登录 后发表回答