Android SQLite auto increment

If speaking for ANDROID, yes, above answers are correct, except naming of the id column.

   database.execSQL("CREATE TABLE IF NOT EXISTS "
                + TableName
                + " ( rowid INTEGER PRIMARY KEY AUTOINCREMENT,  Raqam VARCHAR, ChandBor INT(3));");

It looks like in Android it should be named as 'rowid'. And with Cursor you need to instantiate it like:

Cursor cursorLcl = database.rawQuery("SELECT *," + TableName + ".rowid AS rowid" + " FROM " +
                TableName, null);

Otherwise it didnt work for me. I don't know why it so.


Make it INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL. Here's what the docs say:

If a column has the type INTEGER PRIMARY KEY AUTOINCREMENT then... the ROWID chosen for the new row is at least one larger than the largest ROWID that has ever before existed in that same table.

The behavior implemented by the AUTOINCREMENT keyword is subtly different from the default behavior. With AUTOINCREMENT, rows with automatically selected ROWIDs are guaranteed to have ROWIDs that have never been used before by the same table in the same database. And the automatically generated ROWIDs are guaranteed to be monotonically increasing.


SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.

The keyword AUTOINCREMENT can be used with INTEGER field only. Syntax:

The basic usage of AUTOINCREMENT keyword is as follows:

CREATE TABLE table_name(
   column1 INTEGER AUTOINCREMENT,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
);

For Example See Below: Consider COMPANY table to be created as follows:

sqlite> CREATE TABLE TB_COMPANY_INFO(
   ID INTEGER PRIMARY KEY   AUTOINCREMENT,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Now, insert following records into table TB_COMPANY_INFO:

INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );

Now Select the record

SELECT *FROM TB_COMPANY_INFO
    ID      NAME            AGE     ADDRESS             SALARY
    1       Manoj Kumar     40      Meerut,UP,INDIA     200000.00

Tags:

Sqlite

Android