SqlLiteDatabase.query order by date column not working - android

I'm developing an Android app based on SqlLiteDataBase.
When I query the db using the query method, I want to order by a date column in ascending order.
It seems the ORDERBY is not working.
Cursor cursor = db.query("myTable", // The table to query
dbTools.tableColumns, // The columns to return
whereClause, // 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
"dateText" + " ASC" // The sort order
);
The cursor mquery field during debug shows the following:
SQLiteQuery: SELECT dateText, <some other columns here> FROM myTable WHERE dateText >= '2015-10-01 00:00:00' AND dateText <= '2015-10-31 23:59:59' ORDER BY dateText DESC
(I removed irrelevant columns for your convenience)
After running the query, I want to check whether I have any entry, so I call:
if (!cursor.moveToFirst())
Then I do some logic and whenever I want to move to next row on cursor I run:
if (!cursor.moveToNext())
dateText column is defined as DATETIME:
String query = "CREATE TABLE myTable (id INTEGER PRIMARY KEY AUTOINCREMENT, dateText DATETIME, <other columns here>)";
Can you please advise why the sorting is not working? The rows are not sorted when iterating over the rows on the cursor.
Example:
if I have rows for 1st, 2nd and 10th of November 2015, the sorting by ASC will give this sorting: 10->1->2
Sorting by DESC gives: 2->10->1

here what i propose to you to try :
SQLiteQuery: SELECT dateText, FROM myTable WHERE dateText >= '2015-10-01 00:00:00' AND dateText <= '2015-10-31 23:59:59' ORDER BY date(dateText) DESC
and Be-careful for :
Dest ==> Descendant
ASC ==> Ascendant
Good luck !!

I want to order by a date column in ascending order
But your code show
ORDER BY dateText DESC
Change it ASC is default option, so you can remove it
ORDER BY dateText ASC

Related

Database query android sqlite

I am stuck with one scenario in which I need to do complex query to get cursor. Don't know It is possible or not. Scenario is :
There are three tables in database.
Table Columns
Table-1 _id, name, number, ....
Table-2 _id, table1_id, col1, col2, ....
Table-3 _id, table2_id, col1, col2, ....
In these tables, when any record is inserted in table 2, corresponding table1 id is inserted in that record. Same for table2 id is inserted with table 3 record.
I want cursor for CursorAdapter to display list view of Table-3 data.
Cursor cursor = getContentResolver().query(TABLE_3_NAME, null, null, null, null);
Now need to add selection and selection args of Table-1 in this query.
Is it possible in Android?
You can use raw query to fetch from various tables. One example would be as below.
Cursor mCursor = db.rawQuery("SELECT * FROM Table-1, Table-3 " +
"WHERE Table1.id = <Whatever selection args you want> " +
"GROUP BY Table1.id", null);
This is just an example. You will have to change it as per your requirement.
You can write a SQL selection query (i.e. normal way) and you can execute using rawQuery() method.
For example:
Cursor cursor = db.rawQuery(selectQuery, null);

How do I delete the last row of a SQLite table in Android. I don't have an _id column

Okay, so I have a high score table. I have two columns, Player name and score..
Every time a new score is to be added to the table I delete the last row, put the new score and new player name in the last row and then sort the table according to the score.
I can't delete the row with minimum score because there might be multiple entries with the same score and I don't want to delete all of them.
You might want to rebuild your table and include an id column with integer primary key autoincrement. You can do quite a bit with that column in place (here's an SO question you can look into for that).
Anyway I don't know how your process goes and why you need to delete the last row but here's an example of using an ID column to get the last row ( which I assume would be the latest insert and is what usually happens if you declare an ID integer primary key autoincrement column):
public int LastInsert() {
SQLiteDatabase db = this.getReadableDatabase();
final String MY_QUERY = "SELECT MAX(" + colID + ") FROM " + myTable;
Cursor cur = db.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}
From here you can probably just get the result of LastInsert and use that to direct what your delete function should delete.
Imo you're better of maybe just updating the last row instead of deleting and reinserting in it's place though. Something like this :
public int UpdateAcc(Account acc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(colName, acc.getName());
cv.put(colScore, acc.getScore());
return db.update(myTable, cv, colID + "=?", new String[]{params});
}
I don't remember rather android with sqlite supports multiple commands per statement, but if so this might work:
DELIMITER ;;
SET #LastId = (SELECT ROWID FROM yourTable ORDER BY ROWID DESC LIMIT 1);;
DELETE FROM yourTable WHERE ROWID=#LastId;;
Otherwise you can store this in a integer variable:
SELECT ROWID FROM yourtable ORDER BY ROWID DESC LIMIT 1;
Then use that variable to run the next line
DELETE FROM yourtable WHERE ROWID=#ThatIntegerHere;

Fetching last row from sqlite database

I am trying to fetch the last row from my SQLite database. Until now i have tried max,sql_sequence but nothing seems to work. I have to fetch the row values and assign it to a class variable.
Any help is appreciated as I am new to SQLite and Android.
Thanks..
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
then use cursor to read values
or
do it like this
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
or
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE);
This should do what you want:
SELECT *
FROM food_table
ORDER BY _id DESC
LIMIT 1
Try This It May Help You It Gives Last Record Of Your Table
Cursor mCursor = db.rawQuery("Select * from TableName", null);
mCursor.moveToLast();
Now Get The Data From The Cursor
There is usually a table called sqlite_sequence which stores the highest primary key of all the tables in the SQLite db. So use the following
String selectQuery = "SELECT * FROM sqlite_sequence WHERE name = table_name";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
You can use modified query to in last row....but you have to sort in a order using any column like in my case I have a serial_no column in my Employee table so my query is
SELECT * FROM Employee ORDER BY serial_no DESC LIMIT 1
limit 1 is in your case because you want only last record only

SQLite ORDER BY result of nested query

I have a table with multiple date fields, and I would like to select the rows with the dates closest to the current date, regardless of which column it is.
There are 2 tables in the database;
Covers:
create table covers (_id integer primary key autoincrement, "
+ "stallionName integer not null, mareName integer not null, firstCoverDate text not null, lastCoverDate text not null, "
+ "scan14Date text not null, scan28Date text not null, foalingDate text not null, inFoal integer not null, notes text not null," +
"FOREIGN KEY (stallionName) REFERENCES horses (_id), FOREIGN KEY (mareName) REFERENCES horses (_id))
stallionName and mareName are integers that reference the row _id of the relevant horse in the horse table (As such, the SQL query has multiple joins to get the names for the stallion and mare, instead of just the row _id). All date columns are of the form 'YYYY-MM-DD'
and horses:
create table horses (_id integer primary key autoincrement, "
+ "name text not null, type integer not null, birthDate text not null, vaccineDate text not null, "
+ "inFoal integer not null, notes text not null)
type is an integer referencing a spinner position (type is either mare, stallion, gelding etc)
I want to select 5 rows from the covers table with values of scan14Date, scan28Date and foalingDate that are nearest to today's date (i.e. the 5 most urgent rows)
This is my effort so far;
SELECT covers.* horses1.name AS stallionNameText, horses2.name AS mareNameText
FROM horses horses1 JOIN covers ON horses1._id = covers.stallionName JOIN horses horses2 ON horses2._id = covers.MareName
WHERE covers._id IN
(SELECT DISTINCT _id FROM
(SELECT covers.scan14Date AS date, covers._id
FROM covers
WHERE date > dateToday
UNION
SELECT covers.scan28Date AS date, covers._id
FROM covers
WHERE date > dateToday
UNION
SELECT covers.foalingDate AS date, covers._id
FROM covers
WHERE date > dateToday
ORDER BY date)
LIMIT 5)
(It can be assumed that 'dateToday' is also of the form YYYY-MM-DD. It's sorted out in java)
Now, the nested query below successfully selects the 5 'most urgent' row _ids;
(SELECT DISTINCT _id FROM
(SELECT covers.scan14Date AS date, covers._id
FROM covers
WHERE date > dateToday
UNION
SELECT covers.scan28Date AS date, covers._id
FROM covers
WHERE date > dateToday
UNION
SELECT covers.foalingDate AS date, covers._id
FROM covers
WHERE date > dateToday
ORDER BY date)
LIMIT 5)
And the first section successfully gets all the data for the row _id selected above;
SELECT covers.* horses1.name AS stallionNameText, horses2.name AS mareNameText
FROM horses horses1 JOIN covers ON horses1._id = covers.stallionName JOIN horses horses2 ON horses2._id = covers.MareName
WHERE covers._id IN
....
The issue I'm having is that the order of the row _ids returned by the nested query is lost in the overall query. If for example the nested query returns the row _ids (6, 3, 4, 12, 15) the overall query displays it in the order (3, 4, 6, 12, 15)
I would then like to return the stallion name, mare name, lastCoverDate, 14ScanDate, 28ScanDate and foalingDate.
My question is how can I maintain the order returned by the inner query? I naively tried to add ORDER BY date at the very end, but it predictably says there is no such column.
Thankyou for taking the time to read.
(Also, I'm sure that my SQL query won't be the most efficient way of doing it, but I'm fairly new to all this)
Include the date in the result of the inner query, then you can order by date in the outer query. Your Java wrapper can simply ignore the date field in the result.

rawquery() issue

I am using rawquery() for perform inner join, but this is not giving me any error and does not working, if i use this query directly into sqlite browser than this is working but in application this query does not work, following is my code, sorry for bad English communication
public void deleteFifo() {
final String MY_QUERY1 = "Delete from Items where res_id in (select _id from Favourite where _id not in (select _id from Favourite order by date desc limit 50))";
final String MY_QUERY2 = "Delete from Favourite where _id not in (select _id from Favourite order by date desc limit 50)";
db.rawQuery(MY_QUERY1, null);
db.rawQuery(MY_QUERY2, null);
}
Try:
db.delete(TableName, whereCondition, null);
i.e. in your case
db.delete("Items", "res_id in (select _id from Favourite where
_id not in (select _id from Favourite order by date desc limit 50))", null);
and
db.delete("Favourite ","_id not in (select _id from Favourite
order by date desc limit 50)");
Hope it helps !!

Categories

Resources