6

I am trying to fetch the last row from my SQLite database. Until now i have tried max,sql_sequence but nothing seems to work. I have to fetch the row values and assign it to a class variable. Any help is appreciated as I am new to SQLite and Android. Thanks..

user2574903
  • 89
  • 1
  • 1
  • 8
  • do you have an autoincrement id? what column are you using the MAX operator over? – conca Jul 16 '13 at 02:32
  • yes i have my KEY_ROW_ID="_id" which is autoincremented. I used SELECT * FROM food_table WHERE _id = (SELECT MAX(_id) FROM food_table – user2574903 Jul 16 '13 at 02:46
  • Does this answer your question? [How to get Last record from Sqlite?](https://stackoverflow.com/questions/9902394/how-to-get-last-record-from-sqlite) – WinEunuuchs2Unix Feb 27 '21 at 14:22

5 Answers5

13

If you have already got the cursor, then this is how you may get the last record from cursor:

cursor.moveToPosition(cursor.getCount() - 1);

then use cursor to read values

or

do it like this

Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();

or

SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE);
nandur
  • 134
  • 10
Shakeeb Ayaz
  • 6,200
  • 6
  • 45
  • 64
3

This should do what you want:

SELECT *
FROM food_table
ORDER BY _id DESC
LIMIT 1
mvp
  • 111,019
  • 13
  • 122
  • 148
  • Thanks for the help but I am still not getting it. I get android.database.CursorIndexOutOfBoundsException: Index -1 requested with a size of 1 – user2574903 Jul 16 '13 at 03:02
  • Can you execute this same statement from command line? In adb shell, try to execute `sqlite3 yoursqlitedatabase.db`, and then type and execute statement above. Maybe your database does not exist? – mvp Jul 16 '13 at 03:06
  • 1
    Thanks a ton for investing your precious time in helping me out. The solution by user123 helped.. :) – user2574903 Jul 16 '13 at 03:11
1

Try This It May Help You It Gives Last Record Of Your Table

Cursor mCursor = db.rawQuery("Select * from  TableName", null);
mCursor.moveToLast();

Now Get The Data From The Cursor

Karan Mavadhiya
  • 1,042
  • 8
  • 23
1

There is usually a table called sqlite_sequence which stores the highest primary key of all the tables in the SQLite db. So use the following

String selectQuery = "SELECT  * FROM  sqlite_sequence WHERE name = table_name";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
aphoe
  • 2,586
  • 1
  • 27
  • 31
0

You can use modified query to in last row....but you have to sort in a order using any column like in my case I have a serial_no column in my Employee table so my query is

SELECT * FROM Employee ORDER BY serial_no DESC LIMIT 1

  • limit 1 is in your case because you want only last record only
Bhupesh Kumar
  • 240
  • 2
  • 14