12

Can I create a database constraint on a TEXT column in SQLite disallowing the value of the column to be empty string ""?

I want to allow the column to be null, but disallow empty string.

3 Answers 3

17

Yes you can:

sqlite> create table foo (bar TEXT, CHECK(bar <> ''));
sqlite> insert into foo values (NULL);
sqlite> insert into foo values ('bla');
sqlite> insert into foo values ('');
Error: constraint failed
Sign up to request clarification or add additional context in comments.

2 Comments

What does <> mean?
<> is the SQL equivalent of "not equal to" (!=)
6

You can use a CHECK constraint (http://www.sqlite.org/lang_createtable.html):

SQLite version 3.5.9
Enter ".help" for instructions
sqlite> create table example(col, CHECK (col is null or length(col) > 0));
sqlite> insert into example values ('');
SQL error: constraint failed
sqlite> insert into example values (null);
sqlite> insert into example values ('sample');
sqlite> .nullvalue NULL
sqlite> select col from example;
NULL
sample

Comments

1

As far as i know doesn't exist a similar constraint in SQLite, but maybe you can workaround with a Trigger that on INSERT and/or UPDATE automatically change the string empty in NULL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.