barry
barry

Reputation: 4147

SQLite MAX on Android

I have a database which has a table recording when a vehicle was last fuelled up. It has a date column of type integer.

I need to be able to determine which was the last fuel up date. I am using:

Cursor cursor = db.query(FUEL_USE_TABLE_NAME, LAST_FUEL_UP_DATE_CLAUSE,
            REGISTRATION_NO_COLUMN + "=? ", new String[]{registrationNumber}, 
            null, null, null);

where LAST_FUEL_UP_DATE_CLAUSE is MAX(date_time), where date_time is the name of the column in question.

This works fine when there are entries in the table, but whilst writing a unit test I expected the cursor's row count to be zero when there were no entries in the table, but instead I get a single row with value zero. I.e. the maximum value in the date_time column is zero, when in fact there are no values.

I'm happy to code around this (use 0 to signify no records instead of -1), but would like to know if this is expected behaviour, or am I doing something wrong.

Upvotes: 1

Views: 896

Answers (1)

Barak
Barak

Reputation: 16393

It seems it is expected behavior.

See SQLite documentation here

Specifically it says:

max(X)

The max() aggregate function returns the maximum value of all values in the group. The maximum value is the value that would be returned last in an ORDER BY on the same column. Aggregate max() returns NULL if and only if there are no non-NULL values in the group.

Upvotes: 1

Related Questions