Fetching last row from sqlite database - android

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

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);

SQLite query give different result from mysql

I have two table in my sqlite db here is the first table named supplier and here is the second table named product
what I want to do is I want to get the supplier_name in table product by selecting id_supplier in table_product. Here is my query SELECT table_supplier.id_supplier, table_supplier.supplier_name from table_invoice_in, table_supplier where table_invoice_in.id_product = '4' and table_supplier.id_supplier = table_invoice_in.id_supplier
and what I got from that query is I can get the id_supplier but supplier_name gives me 0 value, but when I try the query in mysql, I got the correct result. My question is :
Is this a limitation of sqlite or there are something wrong with my query?
Thank you in advance.
Try using a JOIN:
SELECT table_supplier.id_supplier, table_supplier.supplier_name FROM table_supplier JOIN table_invoice_in ON table_supplier.id_supplier = table_invoice_in.id_supplier WHERE table_invoice_in.id_product = '4'
The problem solved! When we try to query some column(s) from multiple table, make sure that we get the desired result by pointing directly to the column name. Here is my correct code
public Cursor SelectInvoiceInById(String id){
String query = "SELECT product_name from table_product, table_invoice_in where table_invoice_in.id_invoice_in = '"+ id + "' and table_product.id_product = table_invoice_in.id_product";
ReadDB();
cursor = database.rawQuery(query, null);
cursor.moveToFirst();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Log.d("RESULT", String.valueOf(cursor.getString(cursor.getColumnIndex(SQLiteHelper.PRODUCT_NAME))));
cursor.moveToNext();
}
}
CloseDB();
return cursor;
}

Is There a way to know if the database is empty?

Im Working with SQLiteDatabase and i want to create only 1 row on the database, so i wana use if statement for this, my question is if there is a way to know if the database is empty or not.
Thank you!
EDIT:
I'll update my answer to help you a little bit further.
If you want to find out if the table exists and if it has rows:
Cursor query = myDB.rawQuery("SELECT count(*) FROM sqlite_master WHERE name = 'table1'", null);
if (query.moveToFirst()) {
// If that table exists, check if it has any rows
query = myDB.rawQuery("SELECT count(*) FROM table1", null);
if (query.moveToFirst()) {
// Table exists and it has rows. Do something with them here.
}
}

last elements of table in Sqlite

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.

What is the sql query in SQLite, to retrieve the records from the database table for the last week, for the last month, and for the last year

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

Categories

Resources