user3270537
user3270537

Reputation:

android sqlite orderby datetime always fetches 1st row

I am storing date and time in column of type DATETIME. After that I am trying to retrieve the earliest time. I am using this query

String query_to_fetch_earliest="select *  from "+TABLE_NAME+" order  by datetime("+KEY_DATETIME+") DESC LIMIT 1";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query_to_fetch_earliest, null); 

But i always endup getting 1st row. Please help.

Upvotes: 1

Views: 968

Answers (2)

Luca Sepe
Luca Sepe

Reputation: 2445

Try this:

String query = "SELECT * FROM " +
  TABLE_NAME +
  " WHERE " + 
  KEY_DATETIME +
  " IN (SELECT max(" +
  KEY_DATETIME +
  ") FROM " +
  TABLE_NAME +
  ")"

Upvotes: 0

Sekhar Madhiyazhagan
Sekhar Madhiyazhagan

Reputation: 889

Don't set limit, just do as below

  String query_to_fetch_earliest="select *  from "+TABLE_NAME+" order  by         datetime("+KEY_DATETIME+") DESC ";
  SQLiteDatabase db = this.getWritableDatabase();
  Cursor cursor = db.rawQuery(query_to_fetch_earliest, null); 

Upvotes: 3

Related Questions