Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a unique ID into each SQLite row?

I have the following SQLite code. How do I insert an auto generating unique ID into each row?

    tx.executeSql('DROP TABLE IF EXISTS ENTRIES');     tx.executeSql('CREATE TABLE IF NOT EXISTS ENTRIES (id unique, data)');      tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (1, "First row")');     tx.executeSql('INSERT INTO ENTRIES (id, data) VALUES (2, "Second row")'); 
like image 549
say Avatar asked Feb 18 '12 14:02

say


People also ask

How do I create a unique field in SQLite?

Introduction to SQLite UNIQUE constraint To define a UNIQUE constraint, you use the UNIQUE keyword followed by one or more columns. You can define a UNIQUE constraint at the column or the table level. Only at the table level, you can define a UNIQUE constraint across multiple columns.

How do we call the unique identifier of a table row?

In a relational database, a candidate key uniquely identifies each row of data values in a database table. A candidate key comprises a single column or a set of columns in a single database table.


1 Answers

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.

like image 106
Andomar Avatar answered Sep 23 '22 12:09

Andomar