본문 바로가기
mindmap-search

SQLite3_ Autoincrement생성 방법

by 돌프홍 2009. 3. 16.
(1) How do I create an AUTOINCREMENT field.

Short answer: A column declared INTEGER PRIMARY KEY will autoincrement.

Here is the long answer: If you declare a column of a table to be INTEGER PRIMARY KEY, then whenever you insert a NULL into that column of the table, the NULL is automatically converted into an integer which is one greater than the largest value of that column over all other rows in the table, or 1 if the table is empty. (If the largest possible integer key, 9223372036854775807, then an unused key value is chosen at random.) For example, suppose you have a table like this:

CREATE TABLE t1( a INTEGER PRIMARY KEY, b INTEGER ); 

With this table, the statement

INSERT INTO t1 VALUES(NULL,123); 

is logically equivalent to saying:

INSERT INTO t1 VALUES((SELECT max(a) FROM t1)+1,123); 

There is a new API function named sqlite3_last_insert_rowid() which will return the integer key for the most recent insert operation.

Note that the integer key is one greater than the largest key that was in the table just prior to the insert. The new key will be unique over all keys currently in the table, but it might overlap with keys that have been previously deleted from the table. To create keys that are unique over the lifetime of the table, add the AUTOINCREMENT keyword to the INTEGER PRIMARY KEY declaration. Then the key chosen will be one more than than the largest key that has ever existed in that table. If the largest possible key has previously existed in that table, then the INSERT will fail with an SQLITE_FULL error code.

 

 

※ autoincrement field 를 생성하려면, INTEGER PRIMARY KEY 만 써주면 된다.

   AUTOINCREMENT 추가시는 , table 의 lifetime 동안 유일한 식별자를 보장해 준다. ( 예를 들어, id=30 이라는 로우가 삭제되었을때, id=30을 다시 할당하지 않고 id=31 을 할당한다는 의미.)

 

이 숫자는 9223372036854775807 까지 증가한다.

이것은, 2의 63승 -1 에 해당하는 숫자이고,  1초에 한번씩 데이터가 생성된다고 하더라도, 292471208677년 동안 지속될 수 있다.

 

 

[출처] SQLite AUTOINCREMENT field|작성자 nhlsm


드디어 알아냈다 ...