Restricting displaycount of a row in sqlite table - android

I have two columns in a table. I am using this table in an android application. For ex., TAB1:
when I display One, the display_count of 1 should increment by 1. Like that, I have to display the names continuously through out my application. Mean while, the display_count is getting too big in long run. Is there any option in sqlite, to restrict the column data, such that, if I reach a certain value say display_count = 64 for a row, the display_count should should reset to 1 and again start from 1. To say clearly, display_count should not exceed 64.

Logically while updating, you can use (col=col+1)%65 instead of col=col+1. The thing is count will again start from 0 instead of 1

Related

Possible to store time in SQLite database?

QUESTION: Im making a flashcard app and when the user clicks "easy" for example, I want to increase the time of the card, then that card won't appear until the time goes reaches 0.
e.g. "Card 1" has a time of 0 at default , user clicks "I know button" and the time on that card increases to 5 mins (5:00), then that card wont appear again for 5 minutes until timer is back to 0, is this possible to do?
is this possible to do?
I believe that if you consider what SQLite is capable of and what an Android App is capable of then Yes. However using SQLite alone then No.
Typically, to get your outcome, the time would remain constant in the database but you would extract and thus show only the rows that met the criteria e.g. the time stored is less than or equal to the current time.
Clicking I know would then update the respective row and set the value to the current time plus 5 minutes, thus an extract, which could be timer based would then not show the respective row as it's then greater than the current time.
As for the timer SQLite does not have a built in timer. It is a database manager whose job is to store and retrieve structured data.
As an example consider the following, which shows the principle:-
DROP TABLE IF EXISTS flashcard;
CREATE TABLE IF NOT EXISTS flashcard (cardtitle TEXT, cardtimer INTEGER);
INSERT INTO flashcard VALUES ('Card1',strftime('%s','now')),('Card2',strftime('%s','now','+1 minute')),
('Card3',strftime('%s','now','+2 minute'));
SELECT *,strftime('%s','now') FROM flashcard WHERE cardtimer <= strftime('%s','now');
UPDATE flashcard SET cardtimer = strftime('%s','now','+5 minutes') WHERE cardtitle = 'Card1';
SELECT *,strftime('%s','now') FROM flashcard WHERE cardtimer <= strftime('%s','now');
This:-
drops and creates a table with 2 columns,
a column named cardtitle that stores the title of the card
a column named cardtimer for the time when the card can be displayed on or after
adds 3 rows with unique titles the time fors the first being the current time, the time for the second 1 minute later,and for the third another minute later.
An extract (SELECT query) that displays only the rows where the timer is now or earlier (irrespective of when it is run).
this shows just the first of the 3 rows as the others are in the future
An Update that changes the time of the first row to be 5 minutes from now
Another Extract using the same query as per 3
this shows nothing because now all 3 rows are in the future
Running the above results in :-
i.e. just Card1 is extracted
Then :-
i.e. all of the cards are now in the future.
However if the same extract is then run a while later (but sooner then 5 minutes later), as can be seen some 139 seconds later, then :-
If then after 5 minutes and the same extract is run then :-

Query large table and do logic in code OR do a lot of queries.. Which one is more efficient?

I have a very large table with ~90000 row, each row containing 10 columns.. I need to get some data from the Database.. In the worst case, I need to query 7500 row, but often its around ~4000 rows..
Each row has a column called "LineNumber", and each ~10 rows have the same LineNumber, which starts from 1...
For all the rows that have the same LineNumber, I need to get the Lowest and Highest numbers from a column called RATING..
I can get all those ~4000 rows, and then pass on each one of those lines and do some logic to get the highest or lowest..
OR I can query for each LineNumber I'm interested in and have the query get me the highest and lowest, which will be easier..
Which one of these 2 ways is more efficient?
I would stand for query. At first glance the query looks quite simple:
SELECT LineNumber MIN(RATING) MAX(RATING) FROM <YOUR_TABLE> WHERE... GROUP BY LineNumber
This should give exactly what you want (if I understand right)
I had some problem like you, but in my case was with Dates, geting the 'after' and 'before'...
I did in the code, I query all the data that I need, then I compared the dates, in ~40k lines the time was near 20 sec...
So I tried put the logic in the SQL, when I get the query, I do the the compares, and for my surprise now the query, with all I need do everything in less than 2 sec...
My advice is to try first put the logic in the query, if doesn't satisfactory the results, try in the code and see what's the best.
Good Luck!
[]'s
Bertan

Android - easy/efficient way to maintain a "cumulative sum" for a SQLite column

What is the best way to maintain a "cumulative sum" of a particular data column in SQLite? I have found several examples online, but I am not 100% certain how I might integrate these approaches into my ContentProvider.
In previous applications, I have tried to maintain cumulative data myself, updating the data each time I insert new data into the table. For example, in the sample code below, every time I would add a new record with a value score, I would then manually update the value of cumulative_score based on its value in the previous row.
_id score cumulative_score
1 100 100
2 50 150
3 25 175
4 25 200
5 10 210
However, this is far from ideal and becomes very messy when handling tables with many columns. Is there a way to somehow automate the process of updating cumulative data each time I insert/update records in my table? How might I integrate this into my ContentProvider implementation?
I know there must be a way to do this... I just don't know how. Thanks!
Probably the easiest way is with a SQLite trigger. That is the closest I know
of to "automation". Just have an insert trigger that takes the previous
cumulative sum, adds the current score and stores it in the new row's cumulative
sum. Something like this (assuming _id is the column you are ordering on):
CREATE TRIGGER calc_cumulative_score AFTER INSERT ON tablename FOR EACH ROW
BEGIN
UPDATE tablename SET cumulative_score =
(SELECT cumulative_score
FROM tablename
WHERE _id = (SELECT MAX(_id) FROM tablename))
+ new.score
WHERE _id = new._id;
END
Making sure that the trigger and the original insert are in the same
transaction. For arbitrary updates of the score column, you would have to
have to implement a recursive trigger that somehow finds the next highest id (maybe by selecting by the min id
in the set of rows with an id greater than the current one) and updates its
cumulative sum.
If you are opposed to using triggers, you can do more or less the same thing in
the ContentProvider in the insert and update methods manually, though since
you're pretty much locked into SQLite on Android, I don't see much reason not to
use triggers.
I assume you are wanting to do this as an optimization, as otherwise you could just calculate the sum on demand (O(n) vs O(1), so you'd have to consider how big n might get, and how often you need the sums).

SQLite UPDATE value with row number possible/options?

Hi i'm working on an SQLite viewer in android using java and shell commands (so commands have to be one line) i've written the layout and viewer and all everything is perfect. I set it up so when a value is long pressed an edit text shows where the user can input the new value and then when okay is pressed it should update the value.
I have the column name, old and new value, database name, table name etc however the issue is allowing them to update the value i've seen things like the where clause but the issue is if a column has the value multiple times (which could very well be the case) it won't know the correct row.
So bear in mind i'm new to sqlite been working with it less than a week. Is there a way i can update the column value with the columns name and row number?
What are my options to update the table.
I also don't really under stand this say i have a table like this (one column)
sample
--------
0
0
0
1
0
1
1
0
How would you update the third row to equal 1? If I did
sqlite3 DATABASEHERE "UPDATE TABLEHERE SET sample='1' WHERE sample='0'"
The where statement describes rows 1, 2, 3, 5, and 8 so there has to be a way to use row number?
Thanks for any help
SQLite gives you access to rowid. So you can write SELECT rowid, col FROM table1 and then use it to update the table :UPDATE TABLEHERE SET sample='1' WHERE rowid=3

autoincrement & decrement integer field are available in sqlite database?

I am fetching my data with id which is Integer primary key or integer.
But after deleting any row...
After that if we make select query to show all.
But it will give force close because one id is missing.
I want that id can itself take auto increment & decrement.
when i delete a record at the end(i.g. id=7) after this i add a row then id must be 7 not 8. as same when i delete a row in middle(i.g. id=3) then all the row auto specify by acceding.
your idea can help me.
Most systems with auto-incrementing columns keep track of the last value inserted (or the next one to be inserted) and do not ever reissue a number (give the same number twice), even if the last number issued has been removed from the table.
Judging from what you are asking, SQLite is another such system.
If there is any concurrency in the system, then this is risky, but for a single-user, single-app-at-a-time system, you might get away with:
SELECT MAX(id_column) + 1 FROM YourTable
to find the next available value. Depending on how SQLite behaves, you might be able to embed that in the VALUES list of an INSERT statement:
INSERT INTO YourTable(id_column, ...)
VALUES((SELECT MAX(id_column) + 1 FROM YourTable), ...);
That may not work; you may have to do this as two operations. Note that if there is any concurrency, the two statement form is a bad ideaTM. The primary key unique constraint normally prevents disaster, but one of two concurrent statements fails because it tries to insert a value that the other just inserted - so it has to retry and hope for the best. Clearly, a cell phone has less concurrency than, say, a web server so the problem is correspondingly less severe. But be careful.
On the whole, though, it is best to let gaps appear in the sequence without worrying about it. It is usually not necessary to worry about them. If you must worry about gaps, don't let people make them in the first place. Or move an existing row to fill in the gap when you do a delete that creates one. That still leaves deletes at the end creating gaps when new rows are added, which is why it is best to get over the "it must be a contiguous sequence of numbers" mentality. Auto-increment guarantees uniqueness; it does not guarantee contiguity.

Categories

Resources