26

I am currently working on an Android project in Eclipse and i am having problems with my SQL query.

I am trying to order the query by more than two columns, currently i am doing it by KEY_DAY_ID but i want to also do it by KEY_START_TIME, but i can't get it to work

my query currently looks like this:

Cursor cursor = db.query(TABLE_SESSION, new String[] {KEY_ID, KEY_MODULE_CODE, 
            KEY_DAY_OF_WEEK, KEY_START_TIME, KEY_DURATION, KEY_SESSION_TYPE, KEY_ROOM},
            null, null, null, null, KEY_DAY_ID  + " ASC");

Please let me know your thoughts. Thank you in advance!

1
  • KEY_DAY_ID + ", " + KEY_START_TIME (ASC is default) - should sort by day_id first and then by start_time
    – zapl
    Commented Apr 20, 2012 at 22:20

3 Answers 3

47

The last parameter in db.query() method is the order by clause (without the "order by"). All you need to do is separate both columns by a ",". So it would look like:

Cursor cursor = db.query(TABLE_SESSION, new String[] {KEY_ID, KEY_MODULE_CODE, 
        KEY_DAY_OF_WEEK, KEY_START_TIME, KEY_DURATION, KEY_SESSION_TYPE, KEY_ROOM},
        null, null, null, null, KEY_DAY_ID + " ASC, " + KEY_START_TIME  + " ASC");
2
  • 1
    So which one has higher priority during sorting?
    – Ziwei Zeng
    Commented Oct 4, 2016 at 23:44
  • 3
    @AllenZeng the first one. Commented Oct 16, 2016 at 18:37
2

Also you can do it in select line like this:

Cursor data = ddbb.rawQuery("SELECT * FROM vacations ORDER BY NAME ,MONTH , date ",null);

in previous code the first probability for the first column "NAME" then will start arrange by the Second probability "MONTH" then the third "date"..... which mean working in series
Or:

Cursor data = ddbb.rawQuery("select * from vacations where NAME = ? ORDER BY MONTH AND date ",new String[]{ns});

in previous code by using "AND" the two conditions are working together in parallel

1

This works for me

SQLiteCursor cursor = (SQLiteCursor) db.query(DbHelper.TIMES, colmn, null, null, null, null, DbHelper.TABLE_DAY + " ASC, " + DbHelper.TABLE_LECTURE_NO + " ASC",null);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.