I have an SQLite database in my iOS application. I’m trying to use the SQL function MAX()
- (void) getMaxTime {
if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK)
{
NSString *maxTimeStatement = [NSString stringWithFormat:@" SELECT max(NUMBERS) FROM TIMINGS"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(timingsDatabase, [maxTimeStatement UTF8String], -1, &statement, nil) == SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW) {
massimo = sqlite3_column_int(statement, 0);
NSLog(@"The maximun time is %d seconds ", massimo);
}
sqlite3_finalize(statement);
sqlite3_close(timingsDatabase);
}
}
All the numbers in the column NUMBERS have 6 digits after the coma.
Everything works fine if all the numbers are > 10 or all the numbers are <10.
But (example) when I try to get the max among:
- 1.339670
- 2.955537
- 11.355558
It prints: “The maximun time is 2 seconds” (instead of 11)! I’m struggling to understand why.
*EDIT
This is how my Database was created:
-(void)createDatabase
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"timings.db"]];
if ([[NSFileManager defaultManager] fileExistsAtPath:databasePath] == FALSE)
{
if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK)
{
const char *sqlStatement = "CREATE TABLE IF NOT EXISTS TIMINGS (ID INTEGER PRIMARY KEY AUTOINCREMENT, TIMESTAMP TEXT, TIMING TEXT, NUMBERS TEXT)";
char *error;
sqlite3_exec(timingsDatabase, sqlStatement, NULL, NULL, &error);
sqlite3_close(timingsDatabase);
}
}
}
And this is how timings are stored:
-(void)storeTiming
{
if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK)
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO TIMINGS (TIMESTAMP, TIMING, NUMBERS) VALUES (\"%@\", \"%@\", \"%f\")", [dateFormatter stringFromDate:startDate], stopWatchLabel.text , intervallo] ;
char *error;
sqlite3_exec(timingsDatabase, [insertStatement UTF8String], NULL, NULL, &error);
sqlite3_close(timingsDatabase);
}
}
Seems that column’s data type is string… You should change it to float to use MAX() function.