I have a table which has columns
_id = Primary Key Auto Increment
Title = String
timestamp = long
I have 35 entries in my table. My table can contain only 25 entries at any given time. So that means have of knock off 10 extra entries from my table.
Also 35 entries should be first sorted by timestamp and the last 10 entries should deleted so that i have just 25 recent entries.
Can some please help me with a delete query that first sorts the entries by timestamp and keeps only 25 entries, deleting the rest.
DELETE FROM MYTABLE WHERE _id NOT IN
(SELECT _id from MYTABLE ORDER BY timestamp DESC LIMIT 25)
Keeps the latest 25 entries.
It sounds like you need a FIFO queue in SQL. A table that only stores the most recent 25 (or any other number of) items.
If so, then here is a solution:
http://www.xaprb.com/blog/2007/01/11/how-to-implement-a-queue-in-sql/
Alternative to radashk method:
You can delete one (oldest) record every time you insert a new record, it can be done in DB table trigger on insert:
DELETE FROM MYTABLE WHERE timestamp = MIN(timestamp);
this statement can be wrapped in record count check or something else to make sure that you maintain your minimum record count.
Related
I have created a recently viewed items table. In that I would like to delete the first 20 items how do I go about deleting them?
First in the sense here the first 20 items that was created.
I know the query:
DELETE FROM table ORDER BY id DESC LIMIT 20, 18446744073709551615; (this is random number)
How do I write this in Android format by using DB.Dlete
SQLiteDatabase db = this.getWritableDatabase();
//DELETE FROM table ORDER BY id DESC LIMIT 20, 18446744073709551615;
db.delete(TABLE_RECENT_VIEWED, "ORDER BY " + KEY_RECENTVIEWED_ID_LOCAL + " DESC LIMIT 10, 18446744073709551615", null);
db.close();
I keep getting E/SQLiteLog: (1) near "ORDER": syntax error
Can somebody guide me delete only first 20 records? (for example i have 40 records of which 1 is first record and 40 is the last record.)
Not sure where I am going wrong?
Thanks!
What you want: delete the FIRST 20 ROWS
First you will have to get that rows by:
SELECT Id
FROM table
ORDER By Id ASC
LIMIT 20
You should be using ascending (ASC) in the order by, if you really want the first 20 rows. If you use descending (DESC), that would be the last 20 rows.
After that, you can now delete the records by:
DELETE FROM table
WHERE Id IN (
SELECT Id
FROM table
ORDER By Id ASC
LIMIT 10
)
I'm using sqlite3 as a caching tool for an android app.
Basically, a services fetches data from a server at a regular interval and inserts the new records inside a sqlite3 table. The data is then used to populate UI inside activities and fragments.
Because the data is short-lived, it does not need to be persisted long-term.
In order to save space and resources, how can I make sure that say, only the 100 most recent records are kept and older entries are automatically deleted ?
I've heard of TRIGGERS but not too sure about how to implement them. Any pointers would be appreciated.
Follow the steps
1) Add one column in your table "timestamp"
2) During insert the record set the "timestamp" with current time in milliseconds.
3) Create Trigger like this
CREATE TRIGGER yourtriggername AFTER INSERT
ON yourtable WHEN (SELECT COUNT(*) FROM yourtable) >100
BEGIN
DELETE FROM yourtable WHERE timestamp = (SELECT MIN(timestamp) FROM yourtable)
END
4) Replace "yourtable" with actual table name
5) The above trigger will called every time and check whether the total records in table exceeds 100 it will remove the record whose "timestamp" is minimum.
select entry_id
from entries
order by create_date desc
limit 1 offset 100;
delete from entries where create_date <
(select create_date from entries where entry_id = obtained_entry_id);
Or just:
delete from entries where create_date <
(select create_date from entries by create_date desc limit 1 offset 100);
Trigger to enforce it:
CREATE TRIGGER truncate_entries AFTER INSERT ON entries
BEGIN
--the delete statement from above
END;
Anyone know of a way to limit the number of rows deleted when using an sql DELETE statement?I just need to delete a row that holds a certain value one time instead of deleting every instance of the value. It's my understanding that the LIMIT clause cannot be added to DELETE statements in SQLITE. Now, I can't see a way to limit the number of rows deleted just using _id because I don't know what row _id will be deleted ahead of time; the rows are being deleted based on a value held in a variable and they could be anywhere in the DB. I hope this makes sense. Here's the delete statement:
String sql = "DELETE FROM strategyTotal WHERE strategy_prices = (?)" ;
db.execSQL(sql, new Double[] {subtractedStrategyPrice });
Use a subquery:
String sql = "DELETE FROM strategyTotal WHERE _id IN (SELECT _id FROM strategyTotal WHERE strategy_prices = (?) LIMIT 1);" ;
db.execSQL(sql, new Double[] {subtractedStrategyPrice });
delete from tablename where rowid in (
select rowid from tablename condition LIMIT 1)
try above work around or you may need to enable SQLITE ENABLE UPDATE DELETE LIMIT
my query is just an example. replace it with your own query.
I want to get the latest 5 records in my table, so far i tried this but, it did not work out very well. So, what is the cleanest and efficient way to get last 5 records in the table ?
"select * from (select * from People order by Date DESC limit 5) order by Date ASC;"
Your query works just fine.
To make it efficient, ensure that there is an index on the Date column; then SQLite will just read the last five entries from the index and the table and does not need to scan the entire table.
If this table has an autoincrementing ID column, and if "latest" means the insertion order, then you can use that ID for sorting; this will be as efficient as your original query with an index on Date:
SELECT * FROM (SELECT * FROM People
ORDER BY _id DESC
LIMIT 5)
ORDER BY Date ASC
I use this method to delete a row in my sqlite db:
db.execSQL("delete from "+TABLE_NUMS+" where _ID = '" + this.rowID + "'");
and then I update the rest of Ids to make my entries consecutive:
db.execSQL("UPDATE "+TABLE_NUMS+" set _ID = (_ID - 1) WHERE _ID > "+this.rowID);
And it works fine, but when I add new entries to my DB, the ID of the new entries still add as if the deleted entries existed, say I have 10 rows with IDs starting from 1 to 10, and then I delete number 5 and 6, the rows become 1 to 8, but the new entry's ID will be 11. So my IDs sequence would be 1 to 8 and 11. How can I fix this?
SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. You cam modify that sequence as:
UPDATE SQLITE_SEQUENCE SET seq = this.ID -1 WHERE name = TABLE_NUMS
The same functionality is asked in this question.
The normal ROWID selection algorithm described above will generate
monotonically increasing unique ROWIDs as long as you never use the
maximum ROWID value and you never delete the entry in the table with
the largest ROWID. If you ever delete rows or if you ever create a row
with the maximum possible ROWID, then ROWIDs from previously deleted
rows might be reused when creating new rows and newly created ROWIDs
might not be in strictly ascending order.
http://www.sqlite.org/autoinc.html
This is how SQLite works.
If you really need to have the Ids consecutive don't use autoincrement.
Insert the ids yourself.
You can select MAX(_ID) first to get the last id (greatest value).
This is because you have autoincrement set on _ID when you created the table. So, every row you add will be given a number automatically unless you explicitly set it. If it is absolutely necessary that you need the _IDs in consecutive order, I recommend that you set it yourself instead of using autoincrement.
Here is how to reset it:
delete from your_table;
delete from sqlite_sequence where name='your_table';
This will delete all your data and reset the sequence.
SQLite keeps the largest ROWID in the special SQLITE_SEQUENCE table. You can update that table as:
db.execSQL("UPDATE SQLITE_SEQUENCE SET seq = 0 WHERE NAME = '"+TABLE_NAME+"'");
OR
delete that table as:
db.delete("SQLITE_SEQUENCE","NAME = ?",new String[]{TABLE_NAME});