In SQLite, you cannot add NULL
to INTEGER PRIMARY KEY
and INTEGER PRIMARY KEY AUTOINCREMENT
columns whether or not they have NOT NULL
constraint.
For example, you create test
table with id
column which has INTEGER PRIMARY KEY
or INTEGER PRIMARY KEY AUTOINCREMENT
with or without NOT NULL
as shown below:
CREATE TABLE test (
id INTEGER PRIMARY KEY NOT NULL
);
Or
CREATE TABLE test (
id INTEGER PRIMARY KEY
);
Or:
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
);
Or:
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT
);
Then, you insert 2 rows with NULL
for id
column as shown below:
INSERT INTO test (id) VALUES (NULL);
INSERT INTO test VALUES (NULL);
Now, the numbers 1
and 2
are added instead of NULL
as shown below. *My answer and my answer explain how to show column names and NULL
values respectively:
sqlite> .headers on
sqlite> .mode box
sqlite> .nullvalue NULL
sqlite> SELECT * FROM test;
┌────┐
│ id │
├────┤
│ 1 │
│ 2 │
└────┘
In addition, you create test
table with id
column which has TEXT PRIMARY KEY
with NOT NULL
as shown below:
CREATE TABLE test (
id TEXT PRIMARY KEY NOT NULL
);
Then, you try to insert 2 rows with NULL
for id
column as shown below:
INSERT INTO test (id) VALUES (NULL);
INSERT INTO test VALUES (NULL);
Now, you cannot insert them getting the error below:
Runtime error: NOT NULL constraint failed: test.id (19)
Next, you create test
table with id
column which has TEXT PRIMARY KEY
without NOT NULL
as shown below:
CREATE TABLE test (
id TEXT PRIMARY KEY
);
Then, you insert 2 rows with NULL
for id
column as shown below:
INSERT INTO test (id) VALUES (NULL);
INSERT INTO test VALUES (NULL);
Now, NULL
is added as shown below:
sqlite> .headers on
sqlite> .mode box
sqlite> .nullvalue NULL
sqlite> SELECT * FROM test;
┌──────┐
│ id │
├──────┤
│ NULL │
│ NULL │
└──────┘