Java – SELECT MAX(column) returns only column names

SELECT MAX(column) returns only column names… here is a solution to the problem.

SELECT MAX(column) returns only column names

This confuses me! I’m trying to return the maximum value from a column in my database, but the return value is always the name of that column.

The query I use:

private static final String SELECTMAX = "SELECT MAX(?) FROM " + TABLE_NAME ;

(test) function that returns the maximum value:

public int getMaxValue(String field){

int r = 0;
   String f[] = new String[] {field};
   Cursor c = this.db.rawQuery(SELECTMAX, f);
   if (c.moveToFirst()) {
       String s = c.getString(0);
       Log.i("XXXXX","Max num: " + s); 
   }
   return r;
}

The column I’m querying is of type INTEGER, but the result “s” is always the column name and not the desired value.

Thanks

Solution

I don’t have much experience with sqllite, do I? Parameters of the prepared statement? If so, it looks like you are choosing the maximum value of the string representation of the column name, and the column name should not be passed as a parameter.

So your query should look like this.

SELECT MAX(s) FROM "+ TABLE_NAME;

You are executing effectively

SELECT MAX('s') FROM "+ TABLE_NAME;

Related Problems and Solutions