user3404171
user3404171

Reputation: 113

Select max id column with sqlite

I'm using sqlite in my Android project. I can read/write successfully, but want to select maximum record of Avenue table. My code:

  Cursor c = db.rawQuery("SELECT MAX([Id]) FROM [Avenue];", null);
  c.moveToFirst();
  String result = c.getString(0);

But return null value!

Upvotes: 1

Views: 3420

Answers (2)

Mustafa Poya
Mustafa Poya

Reputation: 3027

To get the maximum value of the ID of a table, you can write your code like this:

public static final String TABLE_NAME = "MY_TABLE";
public static final String KEY_ID = "id";

@SuppressLint("Range")
public int getMaxId(SQLiteDatabase db) {
    String selectQuery = String.format("SELECT MAX(%s) as MAX_ID FROM %s", KEY_ID, TABLE_NAME);

    Cursor cursor = db.rawQuery(selectQuery, null);
    int id = -1;
    if(cursor.moveToFirst()) {
        id = cursor.getInt(cursor.getColumnIndex("MAX_ID"));
    }
    return id;
}

Upvotes: 0

Sadman Sakib
Sadman Sakib

Reputation: 595

public int getLastID()
{
    SQLiteDatabase database=this.getReadableDatabase();
    Cursor cursor = database.rawQuery("SELECT MAX("+COL_NAME+") FROM "+TABLE_NAME, null);
    int maxid = (cursor.moveToFirst() ? cursor.getInt(0) : 0);
    return maxid;
}

This should give you the last/max ID from ur table

Upvotes: 3

Related Questions