Querying the max value of a column in SQLite For Android

Viewed 68192

I have a database created and filed with data. There is a column where i want to find the biggest value.

This is the method used in my database adapter :

public Cursor getBiggestInTheColumn() {
    return db.query(DATABASE_TABLE, null,
                    "MAX(price)", null, null, null, null);
}

It should work but when i call the method :

        cursor = dbadp.getBiggestInTheColumn();

I Get a Runtime Error Like This(LogCat) :

07-14 12:38:51.852: ERROR/AndroidRuntime(276): Caused by: android.database.sqlite.SQLiteException: misuse of aggregate function MAX(): , while compiling: SELECT * FROM spendings WHERE MAX(price)

Any ideas? I suspect this is due to the bad query, but this is the best that i can come up with. Other queries are working well.

7 Answers

If you only want the biggest INTEGER value then you can use the following:

public int getBiggestInTheColumn() {
    return (int) DatabaseUtils.longForQuery(db, "SELECT MAX(price) FROM " + DATABASE_TABLE, null);
}

DatabaseUtils is added in Android API 1

public static long longForQuery (SQLiteDatabase db, String query, String[] selectionArgs)

Utility method to run the query on the db and return the value in the first column of the first row.

Android Developers > DatabaseUtils

Related