How to insert a unique ID into each SQLite row? How to insert a unique ID into each SQLite row? sqlite sqlite

How to insert a unique ID into each SQLite row?


You could define id as an auto increment column:

create table entries (id integer primary key autoincrement, data)

As MichaelDorner notes, the SQLite documentation says that an integer primary key does the same thing and is slightly faster. A column of that type is an alias for rowid, which behaves like an autoincrement column.

create table entries (id integer primary key, data)

This behavior is implicit and could catch inexperienced SQLite developers off-guard.


This is the syntax that I use.

 id INTEGER PRIMARY KEY AUTOINCREMENT,

Simply don't provide data for the autoincrement column

 tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (NULL, "First row")');

Or even simpler

 tx.executeSql('INSERT INTO ENTRIES (data) VALUES ("First row")');


autoincrement is your friend buddy.

CREATE TABLE IF NOT EXISTS ENTRIES (id integer primary key autoincrement, data);INSERT INTO ENTRIES (data) VALUES ("First row");INSERT INTO ENTRIES (data) VALUES ("Second row");

and then:

> SELECT * FROM ENTRIES;1|First row2|Second row