Identity column maximum value in SQLite DBs

前端 未结 4 2402
太阳男子
太阳男子 2021-02-20 02:35

I have a purely academic question about SQLite databases.

I am using SQLite.net to use a database in my WinForm project, and as I was setting up a new table, I got to th

4条回答
  •  情话喂你
    2021-02-20 03:26

    IDENTITY is not actually the proper way to auto-increment in SQLite. That will require you do the incrementing in the app layer. In the SQLite shell, try:

    create table bar (id IDENTITY, name VARCHAR);
    insert into bar (name) values ("John");
    select * from bar;
    

    You will see that id is simply null. SQLite does not give any special significance to IDENTITY, so it is basically an ordinary (untyped) column.

    On the other hand, if you do:

    create table baz (id INTEGER PRIMARY KEY, name VARCHAR);
    insert into baz (name) values ("John");
    select * from baz;
    

    it will be 1 as I think you expect.

    Note that there is also a INTEGER PRIMARY KEY AUTOINCREMENT. The basic difference is that AUTOINCREMENT ensures keys are never reused. So if you remove John, 1 will never be reused as a id. Either way, if you use PRIMARY KEY (with optional AUTOINCREMENT) and run out of ids, SQLite is supposed to fail with SQLITE_FULL, not wrap around.

    By using IDENTITY, you do open the (probably irrelevant) likelihood that your app will incorrectly wrap around if the db were ever full. This is quite possible, because IDENTITY columns in SQLite can hold any value (including negative ints). Again, try:

    insert into bar VALUES ("What the hell", "Bill");
    insert into bar VALUES (-9, "Mary");
    

    Both of those are completely valid. They would be valid for baz too. However, with baz you can avoid manually specifying id. That way, there will never be junk in your id column.

提交回复
热议问题