The question is simple:
In SQLite, if I choose to AutoIncrement a primary key of type NUMERIC
which has a check constraint like CHECK(LENGTH(ID) == 10)
, will it work correctly inserting the first value as 0000000001 and so on?
Asked
Active
Viewed 424 times
0

João Rodrigues
- 191
- 2
- 11
-
Probably not, since you tried it. You did try it? – juergen d Oct 17 '14 at 00:25
-
No I didn't try. I never used SQLite and I am planning with an ER model first. That's why I asked. – João Rodrigues Oct 17 '14 at 00:31
3 Answers
2
No, that does not work. Adding a check does not magically also add a way of fullfilling the check to insert the data.
See this SQLFiddle.

juergen d
- 201,996
- 37
- 293
- 362
1
If you want to restrict the value of an autoincrement column like that, you need to seed the internal sequence table. (There are other ways.)
create table foo (
foo_id integer primary key autoincrement,
other_columns char(1) default 'x',
check (length(foo_id) = 10 )
);
insert into sqlite_sequence values ('foo', 999999999);
Application code is allowed to modify the sqlite_sequence table, to add new rows, to delete rows, or to modify existing rows.
insert into foo (other_columns) values ('a');
select * from foo;
1000000000|a
Trying to insert 11 digits makes the CHECK constraint fail.
insert into foo values (12345678901, 'a');
Error: CHECK constraint failed: foo
One alternative is to insert a "fake" row with the first valid id number immediately after creating the table. Then delete it.
create table foo(...);
insert into foo values (1000000000, 'a');
delete from foo;
Now you can insert normally.
insert into foo (other_columns) values ('b');
select * from foo;
1000000001|b

Mike Sherrill 'Cat Recall'
- 91,602
- 17
- 122
- 185