ORMLITE ORDER_BY with multiple columns - android

I am using ormlite in my recent android project. I want to order by on a query on multiple columns in a table (say two columns). How can I achieve that??
Here is the code for a single order by...
QueryBuilder<Visit, Integer> qb = getHelper().getVisitDao().queryBuilder();
qb.where().eq("FOREIGN_ID", id);
qb.orderBy("VISIT_DATE", false);

I want to order by on a query on multiple columns in a table(say two columns). How can i achieve that??
All you need to do is to call orderBy(...) multiple times.
qb.orderBy("VISIT_DATE", false);
qb.orderBy("order-column", false);
...
This is covered by the documentation. To quote:
Add "ORDER BY" clause to the SQL query statement to order the results by the specified column name. Use the ascending boolean to get a ascending or descending order. This can be called multiple times to group by multiple columns.
Also the javadocs:
Add "ORDER BY" clause to the SQL query statement. This can be called multiple times to add additional "ORDER BY" clauses. Ones earlier are applied first.

Related

Sqlite order by rows order

I am using this query
"select * from SomeTable group by SomeColumn"
It is returns list with accenting order, but i need to same order like in database.
For example the order in database is:
p
a
s
But result is:
a
i
p
Sample
The result need to be like distinct by CityEN but with all columns and order like 1.Paris 2.Amsterdam 3.Istanbul
In Sqlite, each row of a table has a unique rowid, which you can use for sorting.
select * from SomeTable group by SomeColumn order by rowid;
In your statement, add this line to sort the results:
order by min(rowid)
Your query does not enforce any order with ORDER BY clause so no assumption about row order should be made. If you want specific order add i.e. ORDER BY SomeColumn. See docs about all available order options: https://www.sqlite.org/lang_select.html#orderby
By the rules of SQL, you can't count on getting records back in any specific order without specifying an ORDER BY clause in your SQL query.
In practice servers sometimes return values in the order in which they're inserted, in the order of the first index created, or in the order of the primary key--but you can't count on this behavior, and in fact I've seen the behavior change between database maintenance windows or after the database version is upgraded. You definitely wouldn't want to count on a DB engine to give you back records in any particular order if you write a SELECT statement without an ORDER BY clause.
The only real way to get your records back in the order you inserted them is to create a timestamp column and then sort on it during the SELECT. If you don't want to worry about populating that column on INSERT, have that column auto-populate itself with a timestamp (depending on your DB engine).

SQLite too many terms in compound SELECT

In my Android SQLite databese query I have an INSERT INTO statement followed by about 600 ('data1'),('data2')... tags, generated by code.
After db.exec(sql) I got this error: "too many terms in compound SELECT (code1); while compiling INSERT INTO.. "
Is there any way to increase this limitation?
The limit SQLITE_MAX_COMPOUND_SELECT cannot be raised at runtime,
So you need to split your inserts into batches of 500 rows each. This will be more efficient than inserting one row per query. For e.g.
BEGIN TRANSACTION
INSERT INTO tablename (data1,data2) VALUES ("data1","data2")
INSERT INTO tablename (data1,data2) VALUES ("data1","data2")
INSERT INTO tablename (data1,data2) VALUES ("data1","data2")
...
END TRANSACTION
Also see Insert Multiple Rows in SQLite

Android - Request SQLite query to be sorted based on relationship between two columns

Is there any way to query a Cursor with the content sorted based on the row's relationship between two columns?
For example, if I had two columns in my table:
Basketball shots made
Basketball shots attempted
is there any way I query a Cursor with the data sorted based on the "shot percentage" (i.e. made/attempted)?
Note that in order to get accurate sorting, you might need to cast to DOUBLE (the above suggestions does integer division which didn't provide correct results in all cases):
ORDER BY CAST(ShotsMade AS DOUBLE)/ShotsAttempted DESC
In your query, put ORDER BY ShotsMade/ShotsAttempted DESC.

Android SQLite Insert-Select

There are two different methods for inserting a row into table:
execSql, using it I can execute sql statements with SELECT - INSERT. But it doesn't return id of new row.
different inserts - I can get insert-id here, but I can't create insert queries with substitution values from another table.
I can split my query into two, but isn't it slower, than one query?
Do your insert however you like, then execSql "select last_insert_rowid()".

Android's SimpleCursorAdapter with queries using DISTINCT

Here's an interesting question that I'm shocked hasn't been asked more often on the internet. Android's CursorAdapters are extremely useful once you get a ContentProvider up and running and learn how to use it, but they are limited due to their requirement on having the _id field as part of their query (an error is thrown without it). Here's why:
My specific problem is that I have two spinners: One spinner should contain unique "category" names from the database, and the other should populate with all the database entries from the selected "category" (category being the column name, here). This seems like a pretty simple setup that many programs might use, no? Trying to implement that first spinner is where I've run into problems.
Here's the query that I would like for that first spinner:
SELECT DISTINCT category FROM table;
Making this query throws an error on CursorAdapter because the _id column is required as part of the query. Adding the _id column to the projection naturally returns every row of the table, since you're now asking for distinct id's as well, and every id is distinct (by definition). Obviously I would rather see only one entry per category name.
I've already implemented a work around, which is to simply make the query above and then copy the results into an ArrayAdapter. My reason for this post is to see if there was a more elegant solution to this odd little problem and start a discussion on what I could be doing better. Alternate implementation suggestions, such as using different kinds of controls or adapters, are very welcome.
Here's the query I ended up with:
SELECT _id, category FROM table_name GROUP BY category;
I used the rawQuery() function on an SQLiteDatabase object to carry this out. The "GROUP BY" piece was the key towards getting the right results, so thanks to user Sagar for pointing me in the right direction.
Do consider user Al Sutton's answer to this question as well, as it may be a more elegant solution to this problem.
Thanks everyone!
I'd suggest having a separate table with just _id & category in it which contains one row per unique category. Your data rows can then replace their category field with the _id from the category table.
This has the added advantage you can change the category in the categories table and it will show up in all entries in that category.
SELECT DISTINCT category,_id FROM table GROUP BY category;
I think this should give you what you are looking for. The results from this will be the category, and the first _id for that category. You can ignore the second column (_id).
You can specify an _id field alias in your select statement that is just a constant value, for example:
SELECT DISTINCT 0 _id, category FROM table;
Better yet, I solved this problem by using:
SELECT DISTINCT category AS _id FROM table
Now, you have a column with the name _id which has what you want in it

Categories

Resources