I am using the query method of SQLiteDatabase. I need help with the orderBy parameter of this method.
Cursor cursor = sqLiteDatabase.query(tableName, tableColumns, whereClause, whereArgs, groupBy, having, orderBy);
public Cursor getAllCustomexp(int TID) throws SQLException
{
Cursor mCursor =
db.query(false, CEXP_TABLE, new String[] {KEY_CEID, FLD_CETID, FLD_CEEID, FLD_CEMID,
FLD_CEAMT, FLD_CESEL}, FLD_CETID + " = " + TID, null,
null, null, FLD_CEEID, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Question 1:
In the above query the result set will be sorted by FLD_CEEID in ascending or descending order ?
Question 2:
If I need to order the result set first by FLD_CEEID and then by FLD_CEMID how should i construct the order by parameter of this query.
Is it possible to do multiple order by using this method?
From SQLite docs:
If a SELECT statement that returns more than one row does not have an
ORDER BY clause, the order in which the rows are returned is
undefined. Or, if a SELECT statement does have an ORDER BY clause,
then the list of expressions attached to the ORDER BY determine the
order in which rows are returned to the user. Rows are first sorted
based on the results of evaluating the left-most expression in the
ORDER BY list, then ties are broken by evaluating the second left-most
expression and so on. The order in which two rows for which all ORDER
BY expressions evaluate to equal values are returned is undefined.
Each ORDER BY expression may be optionally followed by one of the
keywords ASC (smaller values are returned first) or DESC (larger
values are returned first). If neither ASC or DESC are specified, rows
are sorted in ascending (smaller values first) order by default.
Answer 1: Result set will be sorted in ascending order.
Answer 2:
String orderBy = FLD_CEEID + " ASC, " + FLD_CEMID + " ASC";
db.query(false, CEXP_TABLE, new String[] {KEY_CEID, FLD_CETID, FLD_CEEID, FLD_CEMID,
FLD_CEAMT, FLD_CESEL}, FLD_CETID + " = " + TID, null,
null, null, orderBy, null);
It works like in SQL Select Order By. You can find details here: http://en.wikipedia.org/wiki/Order_by_(SQL) .
Related
I have been trying to get the biggest value of a column. For this I sorted it by DESC so the biggest one comes first, but it turns out that any nulls actually come first for some reason. Therefore I tried to add a WHERE, but it still has nulls in it for some reason and I can't figure out why.
String[] projection = {
DATAbaseContract.DATAbaseEntry.COLUMN_PRICE,
};
String sortOrder =
DATAbaseContract.DATAbaseEntry.COLUMN_PRICE + " DESC";
Cursor DATAbaseCursor = DATAbaseDb.query(
DATAbaseContract.DATAbaseEntry.TABLE_NAME, // The table to query
projection, // The columns to return
ShipsContract.ShipsEntry.COLUMN_PRICE + " IS NOT NULL", // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
if(!DATAbaseCursor.moveToPosition(0)) {return;}
PriceMaxVal=DATAbaseCursor.getInt(DATAbaseCursor.getColumnIndex(DATAbaseContract.DATAbaseEntry.COLUMN_PRICE));
PriceMinVal=0;
How can I make query using SQLiteDatabase.query ?
"Select * from table where col1 = something AND col2 IS NOT NULL"
I tried it by putting the col2 with a =? in selection String and NOT NULL in selection argument but it doesn't work.
Please tell me where m going wrong.
selectionArgs is an array of strings, and can be used only for string values.
When you use col2 = ? with the string NOT NULL, you are telling the database to check if the column's value is the eight-character string "NOT NULL".
You must write col2 IS NOT NULL directly into the selection string:
db.query("MyTable", null,
"col1 = ? AND col2 IS NOT NULL",
new String[] { "something" },
null, null, null);
You can use Cursor and rawQuery
Cursor c=db.rawQuery(your_query,null)
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a Cursor over the result set.
Parameters
table The table name to compile the query against.
columns
A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection
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.
selectionArgs
You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy
A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having
A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy
How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
So you can try like this
String[] args = { "first string", "second#string.com" };
Cursor cursor = db.query("TABLE_NAME", null, "name=? AND email=?", args, null,null,null);
public static final String KEY_HIGH
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_HIGH + " INTERGE);"
);
}
public long createEntry(String high) {
ContentValues cv = new ContentValues();
cv.put(KEY_HIGH, high);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
String[] columns = new String[]{KEY_HIGH,KEY_NAME};
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null, KEY_HIGH + " DESC");
I am trying to sort by the column KEY_HIGH, however, the result came out like this:
4
3
2
10
11
1
How do I sort them as numbers from highest to lowest?
thanks.
From the Android docs:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Added in API level 1
Query the given table, returning a Cursor over the result set.
Parameters
table The table name to compile the query against.
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selection 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.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
Returns
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
See Also
Cursor
Note that the final is named orderBy. This is where you can specify which column (or columns) to sort on. Also note that you do not need to include the "ORDER BY" keywords that you would use in a SQL statement.
I was having the same problem.It has a very simple solution:
In your CREATE_TABLE statement do this: " INTEGER, "+KEY_HIGH+ //your remaining things.
no need for the comma after the last null
Cursor c = ourDatabase.query(
DATABASE_TABLE,
columns, null, null, null, null + " ORDER BY " + KEY_HIGH + " DESC");
I want to retrieve all the records in ascending order with a WHERE clause. But where to include the WHERE condition in my query? It is working fine for ascending order.
Here is my code. First I am working on this query but here I am not able to implement the ORDER BY clause.
Cursor tripdaycursor = sdb.rawQuery(
"select TripDay_Id, Tripday_Date, Tripday_ParsingDate,
Trip_Complete, TripDay_Endkm, TripDay_Count, Tripday_EndPlace
FROM TripDay WHERE Trip_Id="+record, null);
So I tried the code below for ascending order:
String recordid=Integer.toString(record), Trip_Id="Trip_Id", TripDay_Id="TripDay_Id",
Tripday_Date="Tripday_Date", Tripday_ParsingDate="Tripday_ParsingDate",
Trip_Complete="Trip_Complete", TripDay_Endkm="TripDay_Endkm",
TripDay_Count="TripDay_Count", Tripday_EndPlace="Tripday_EndPlace",
TripDay = "TripDay";
Cursor tripdaycursor = sdb.query(TripDay, new String[] {
TripDay_Id, Tripday_Date, Tripday_ParsingDate, Trip_Complete, TripDay_Endkm,
TripDay_Count, Tripday_EndPlace}, null, null, null, null,
Tripday_ParsingDate + " ASC");
But I want both conditions on a single query, with the WHERE clause and in ascending order. How to do that?
You can put "order by Column_Name" in your query after the where clause. Something like this, with the column you want to order by in ascending order
Cursor tripdaycursor = sdb.rawQuery("select TripDay_Id,Tripday_Date,Tripday_ParsingDate,Trip_Complete,TripDay_Endkm,TripDay_Count,Tripday_EndPlace from TripDay where Trip_Id="+record + " order by " + columnName,null);
I have a query that selects rows in a ListView without having a limit. But now that I have implemented a SharedPreferences that the user can select how much rows will be displayed in the ListView, my SQLite query doesn't work. I'm passing the argument this way:
return wDb.query(TABELANOME, new String[] {IDTIT, TAREFATIT, SUMARIOTIT}, CONCLUIDOTIT + "=1", null, null, null, null, "LIMIT='" + limite + "'");
The equals (=) operator is not used with the LIMIT clause. Remove it.
Here's an example LIMIT query:
SELECT column FROM table ORDER BY somethingelse LIMIT 5, 10
Or:
SELECT column FROM table ORDER BY somethingelse LIMIT 10
In your case, the correct statement would be:
return wDb.query(TABELANOME, new String[] {IDTIT, TAREFATIT, SUMARIOTIT}, CONCLUIDOTIT + "=1", null, null, null, null, String.valueOf(limite));
Take a look here at the SQLite select syntax: http://www.sqlite.org/syntaxdiagrams.html#select-stmt
This image is rather useful: http://www.sqlite.org/images/syntax/select-stmt.gif
For anyone stumbling across this answer looking for a way to use a LIMIT clause with an OFFSET, I found out from this bug that Android uses the following regex to parse the limit clause of a query:
From <framework/base/core/java/android/database/sqlite/SQLiteQueryBuilder.java>
LIMIT clause is checked with following sLimitPattern.
private static final Pattern sLimitPattern = Pattern.compile("\\s*\\d+\\s*(,\\s*\\d+\\s*)?");
Note that the regex does accept the format offsetNumber,limitNumber even though it doesn't accept the OFFSET statement directly.
Due to this bug which also doesn't allow for negative limits
8,-1
I had to use this workaround
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(table);
String query = builder.buildQuery(projection, selection, null, null, null, sortOrder, null);
query+=" LIMIT 8,-1";