Beppe Beppe - 5 months ago 12
SQL Question

How can use BETWEEN in sqlite via db.query

I've a query on sqlite that use "between" and I want to use it on standard Query.
my code is here:

String[] columns = new String[]{"_id", "question_group", "question_number", "is_answered"};
String selection = "question_group = ?";
String[] selectionArgs = new String[]{String.valueOf(category)};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.query(TABLE_QUESTION, columns, selection, selectionArgs, groupBy, having, orderBy, limit);


I want to Add another condition that is :question_number between 1 and 10. I can now write this query in a single statement but I want to use it as above I told.

Answer

From the SQLite documentation describing the selection parameter of the query() method:

A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.

If you want the following WHERE clause in your query

 WHERE question_group = :category AND question_number BETWEEN 1 AND 10

then you can use the following selection and selectionArgs:

String selection = "question_group = ? AND question_number BETWEEN ? AND ?";
String[] selectionArgs = new String[]{ String.valueOf(category), "1", "10"};