How can i get the last N elements of a table?
I have used this query but it does not seem to work.
Cursor c = database.rawQuery("select top 7 * from dailystats order by daily_ID desc;", null);
For earning the point, I make my comment as an answer as requested by the OP;)
use limit, select * from dailystats order by daily_ID desc LIMIT 7
Just use limit:
select * from dailystats order by daily_ID desc limit 7;
Top is for SQL Server You need to use Limit
select * from dailystats order by daily_ID desc limit 7;
OR to Select just the last row
select * from dailystats where daily_ID = (select max(daily_ID) from dailystats);
If you allow me to convert all those answers to more Android-code like:
SQLiteDatabase database = dbHelper.getReadableDatabase();
String tableName = "dailystats";
String orderBy = "daily_ID desc";
String limit = String.valueOf(5);
Cursor cursor = database.query(tableName,
null, //all columns
null, // no where clause
null, // no where arguments
null, // no grouping
null, // no having
orderBy,
limit);
From then on you use the cursor as any other cursor in Android. It will hold the top limit results with respect to the orderBy column in descending order.
Related
This is my method which return MAX(_id)
public static int getMaxId(Context context, Uri uri, String columnName) {
//it is all
String []projection = new String[]{"MAX("+ columnName +")"};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
cursor.moveToFirst();
return cursor.getInt(0);
}
If count of records in database <127 everything is all right, but if count of records >127 (for example 250 or 500) this method returns 127.
The max() aggregate function returns the maximum value of all values in the group. The maximum value is the value that would be returned last in an ORDER BY on the same column. Aggregate max() returns NULL if and only if there are no non-NULL values in the group.
If you had a column like that, say name it 'myorder', then you could use a
query like this to get the last row:
select * from mytable
where myorder IN (select max(myorder) from mytable)
If you mean get the row that would sort last in a query, then you have
something like this at the end of the query, after the "ORDER BY":
LIMIT 1 OFFSET (select count(*) from mytable) - 1
from here
I am trying to execute a query to retrieve some data from the table.
Below is my query:
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber="+"'myCustomNumber'", null);
where myNumber is type of 'TEXT'
But every time I am getting cursor.getCount() = 0;
It seems there's a mistake in my query.
Please let me know the correct way of writing above query.
In your query the parameter passed as myNumber has become a text due the double quotes around it.
Change it to,
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber = ' " + myCustomNumber + "'", null);
I think you should be use below code :
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber='"+myCustomNumber+"'", null);
i hope it will work for you.
Try this
String phoneNo = "0000000000";
String query = "Select * from where mynumber = '" +phoneNo+ "'";
cursor = myDB.rawQuery(query,null);
you can execute that query i.e.
rawQuery("SELECT * FROM myTable WHERE myNumber= = ? ", new String[] {"myCustomNumber"});
In the query that you have used, the number has not been passed in quotes.
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber="+"'myCustomNumber'", null);
That query would mean myNumber= myCustomNumber literally, and not a variable value.
You need to add the quotes before and after your myCustomNumber like:
cursor = myDB.rawQuery("SELECT * FROM myTable WHERE myNumber="+"'"+myCustomNumber+"'", null);
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
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) .
I created a data base table using SQLite in my project, I want to retrieve records from the database for the last week, for the last month, for the last year, when user click on the specified Buttons. But I don't know how to retrieve the records. Is there any function exist to get these records accordingly ?
You'll need to construct a "where" clause like so:
ContentResolver cr = getContentResolver();
Cursor groupCur = cr.query(
Groups.CONTENT_URI, // what table/content
new String [] {Groups._ID, Groups.NAME}, // what columns
"Groups.NAME NOT LIKE + 'System Group:%'", // where clause(s)
null, // ???
Groups.NAME + " ASC" // sort order
);
I spaced this out so it's easier to explain, but this is what you typically see as:
Cursor groupCur = cr.query(Groups.CONTENT_URI, null, null, null, null);
I found the query
SELECT * FROM DATABASE_TABLE
WHERE strftime('%Y-%m-%d',DATE) >= date('now','-6 days') AND
strftime('%Y-%m-%d',DATE)<=date('now') order by DATE