6

I have a sqlite table (sqlite version 3.7.3) where nulls inserted into the primary key column are being undesirably auto-incremented:

sqlite> CREATE TABLE foo(bar INTEGER NOT NULL PRIMARY KEY);
sqlite> INSERT INTO foo(bar) VALUES(NULL);
sqlite> SELECT * FROM foo;
1

In the sqlite docs, it shows that adding the AUTOINCREMENT keyword to the column should create this behavior, but there doesn't appear to be a keyword to prevent the auto incrementing...

I also found that I can build sqlite with the SQLITE_OMIT_AUTOINCREMENT compile option, but I don't want to disable the behavior globally, just for this particular column.

Interestingly, if I don't include the PRIMARY KEY constraint, I get the desired behavior:

sqlite> CREATE TABLE FOO(bar integer NOT NULL);
sqlite> INSERT INTO FOO(bar) VALUES(NULL);
SQL error: foo.bar may not be NULL

How can I define the table so that NULL values are rejected and keep the primary key constraint?

bigdogwillfeed
  • 140
  • 1
  • 8

2 Answers2

9

Autoincrement behavior applies only to columns declared as INTEGER PRIMARY KEY. So the easiest ways to disable it are:

  • Declare the column as UNIQUE instead of PRIMARY KEY.
  • Declare the column type as INT instead of INTEGER.

Note that either one will give you a column with integer affinity instead of being constrained to contain only integers.

dan04
  • 87,747
  • 23
  • 163
  • 198
  • 2
    You probably also want to combine the UNIQUE with NOT NULL to prevent creation of "idless" records in your table. – Timo May 04 '16 at 13:22
-2

One way to disable autoincrement (outside of recreating the table) when you need to insert data is to use the import tool in sqlite3:

If you have a table like this:

CREATE TABLE [table1] ( [ID] integer PRIMARY KEY AUTOINCREMENT NOT NULL, [col1] TEXT);

If you run the import command on it with your data file:

ID col1
10 abc
20 def

import myfile.txt table1

It will import the rows, and it will disregard the autoincrement feature.

live-love
  • 48,840
  • 22
  • 240
  • 204
  • Does not work for me at least. Tested with `sqlite3 --version 3.8.10.2 2015-05-20 18:17:19 2ef4f3a5b1d1d0c4338f8243d40a2452cc1f7fe4` – Timo May 04 '16 at 13:19