5

I want to get the last inserted row's primary key value which is set automatically(AUTO INCREMENT). I searched over the S/O and found answers for last row_id. But I need the last inserted row's values. Please help me.

Thanks

Mostafa Imran
  • 659
  • 2
  • 9
  • 28

3 Answers3

19

Try this code

String selectQuery = "SELECT  * FROM " + "sqlite_sequence";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();

or

SELECT * 
FROM    TABLE
WHERE   ID = (SELECT MAX(ID)  FROM TABLE);

or

SELECT * FROM table ORDER BY column DESC LIMIT 1;
RAM
  • 2,257
  • 2
  • 19
  • 41
sasikumar
  • 12,540
  • 3
  • 28
  • 48
2

try this :

select * from <TABLE> where row_id = (select max(row_id) from <TABLE>);

or

SELECT * FROM tablename ORDER BY row_id DESC LIMIT 1;
Rathan Kumar
  • 2,567
  • 2
  • 17
  • 24
0

Use moveToLast() in Cursor interface.

From android.googlesource.com

/**
 * Move the cursor to the last row.
 *
 * <p>This method will return false if the cursor is empty.
 *
 * @return whether the move succeeded.
 */
boolean moveToLast();

Simple example:

final static String TABLE_NAME = "table_name";
String name;
//....

Cursor cursor = db.rawQuery("SELECT  * FROM " + TABLE_NAME, null);

if(cursor.moveToLast()){
    name = cursor.getString(column_index);
    //--get other cols values
}

If you want to get data when insert, you can use insert() in SQLiteDatabase class.

private static final String TABLE_NAME = "table_name";
private static final String COLUMN_ONE = "ID";
private static final String COLUMN_TWO = "NAME";

long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();

ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_TWO, name);//name is a variable for data value

row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred 

Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ID = ?", new String[] { row+"" });
while (res.moveToNext()) {//there is no need to use while, if condition is good.
    System.out.println(res.getString(0));//I just sout to avoid more code.
    System.out.println(res.getString(1));
}

This is post is about autoincrement, if you want to read.

Blasanka
  • 21,001
  • 12
  • 102
  • 104