How can SQLite require a value while still allowing an empty string?
Quick answer
Use NOT NULL to reject a missing SQL value (NULL), and allow '' if an empty string is acceptable. If the value must have nonzero length, add CHECK(length(value) > 0). If it must contain something other than ordinary spaces, use CHECK(length(trim(value)) > 0); SQLite’s default trim() removes ordinary spaces at the ends, not every possible whitespace character. [S1] [S2]
The question, the details, the next step.
A practical checklist
Decide whether
''is valid; useNOT NULLalone if it is.If empty text must fail, add
CHECK(length(label) > 0).If ordinary spaces alone must fail, consider
CHECK(length(trim(label)) > 0).Specify whether the rule covers only ordinary spaces or other whitespace too.
Check the expected outcomes for
NULL,'', spaces, and ordinary text against your intended rule.
A few more useful answers
Does `NOT NULL` reject an empty string in SQLite?
No. NOT NULL rejects SQL NULL; it does not by itself reject an empty text value. [S1]
Does `length(trim(label)) > 0` reject every whitespace-only string?
Not necessarily. SQLite’s default trim() removes ordinary spaces at the ends, and should not be described as removing every possible whitespace character. [S2]
Which constraint should I use if an empty string is allowed?
Use NOT NULL without a nonempty-text check. That rejects NULL while allowing ''. [S1]
Sources
References used for this guide.
- [S1] SQLite CREATE TABLE: NOT NULL and CHECK constraints sqlite.org · Checked
- [S2] SQLite Built-In Scalar SQL Functions: trim sqlite.org · Checked
