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?
AUTO INCREMENT FieldAuto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
The advantages to using numeric, auto incremented primary keys are numerous, but the most impactful benefits are faster speed when performing queries and data-independence when searching through thousands of records which might contain frequently altered data elsewhere in the table.
On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually one more than the largest ROWID currently in use. This is true regardless of whether or not the AUTOINCREMENT keyword is used.
One of the important tasks while creating a table is setting the Primary Key. The Auto Increment feature allows you to set the MySQL Auto Increment Primary Key field. This automatically generates a sequence of unique numbers whenever a new row of data is inserted into the table.
Autoincrement behavior applies only to columns declared as INTEGER PRIMARY KEY
. So the easiest ways to disable it are:
UNIQUE
instead of PRIMARY KEY
.INT
instead of INTEGER
.Note that either one will give you a column with integer affinity instead of being constrained to contain only integers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With