Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent autoincrementing integer primary key?

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?

like image 984
bigdogwillfeed Avatar asked Jun 11 '13 20:06

bigdogwillfeed


People also ask

Does primary key automatically auto increment?

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.

Should you use auto increment for primary key?

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.

Does primary key auto increment SQLite?

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.

Does MySQL auto increment primary key?

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.


1 Answers

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.

like image 139
dan04 Avatar answered Sep 28 '22 05:09

dan04