Updating records older than n minutes - sqlite

I have a sqlite database with a datatime field called last_accessed and another field called stale.
How do I update the stale field for records older than say 5 minutes?
e.g.
This doesn't seem to work.
update mytable set stale=1 where (datetime('now') - last_accessed) > 300;
In fact
select datetime('now') - '2011-02-22 08:48:34';
returns 0.
How do I do arithmetic in sqlite3?
EDIT:
Since I'm converting last_accessed to a datetime and really it just needs to be a seconds field. Do you think I should convert that field to seconds field instead. Then I won't need to do something like strftime('%s',time('now')) - strftime('%s',last_accessed)?
Edit2:
There is no difftime function as far as I can tell. I discovered you have to use strftime('%s', datetime('now')) - ... format to make it work. However, instead I've converted simply to an integer field where I'm storing time(NULL) directly.

I think it should be
select datetime('now') - datetime('2011-02-22 08:48:34');
or something like that (see the examples).

To answer this question in case others are wondering how to correctly do date/time arithmetic in sqlite.
The correct answer is:
update mytable set stale = 1 where strftime('%s', datetime('now')) - strftime('%s', last_accessed) > 300;
However, I don't actually need the datetime format in the table and have instead opted for a numeric field instead. I'm not seeking any more answers to this question.
Thanks.

Related

OUTPUT <NULL> WHEN SELECTING DATE FROM DATETIME - SQLITE

I'm new to the SQL world and im going crazy trying to figure out how to SELECT date from a datetime field in SQLITE.
Example: value <11/11/2005 14:56>, i just want to select <11/11/2005> for EVERY ROW.
I tried strftime(), date(), CAST() and other functions but the output its always NULL.
For example i tried querying SELECT strftime('%d/%m/%Y' , columnname) AS date FROM tablename;
OUTPUT: "NULL" in every row
Can someone help me understand what im doing wrong and how can i fix it? Thank you!!!
It always returns NULL because MM/DD/YYYY is not a valid sqlite date format. Treat the column as a string and use substr and instr to drop off the time portion. Something like (no guarantees, check the doc!)
SELECT substr(columname,0,instr(columnname,' '))
Re comment "how to order by the date in descending order"
This problem is a good argument (the best argument?) for storing the date in a sqlite date/time format. There is a strategy in this post for converting MM/DD/YYYY to YYYY-MM-DD (which sorts dates correctly).
If it's not too late, it would be advisable to change the date storage to a valid sqlite date format. strftime can be used to present the date as desired, and sorting will be accurate.

SQLite: How to convert a bigint field to date or timestamp?

I've received a SQLite file with .db extension.
Opening it, I have a column with serial numbers: i.e. 1600414704594 (that should correspond to 2020-10-09 and whatsover time)
The db comes from outside and I don't know how that date field has been built.
Could you suggest me a query to get a valid date/time from that db column ?
I've tried reading this post but none of the given solution returned me a valid (and actual) date, please help me.
It looks like an Unix time in milliseconds. SQLite's unixepoch modifier expects it in seconds. The conversion is fairly easy :
SELECT DATETIME(1600414704594 / 1000, 'unixepoch')
2020-09-18 07:38:24

How to correctly use times in SQLITE?

I have a table which runs a DELETE query every few seconds. With that query I want to delete all entries that are older than 30 seconds.
At the moment I have a value for the creation time in my table creationdate integer which contains the date of creation in milliseconds since 1 January 1970.
In my DELETE query that I run every 30 seconds I compare it against the current time:
delete from table where creationdate < strftime('%s', 'now', '-30.0 seconds')
I referred to this article for the strftime formatting.
This query doesn't delete the entries, that's my problem. It works without the where statement so I guess that the function is the problem.
What am I missing out or is there even a better way to solve this problem?
edit: It doesn't work without the -30.0 seconds modifier either, so I think that I misunderstood how strftime works. Referred to this question as well.
I found my problem. I overlooked the fact that in SQLite strftime('%s') returns in SECONDS and not in MILLISECONDS.

SQLite - Ordering

I have a strange issue where upon selecting information from a SQLite database, ans ordering based upon date, the results returned are invalid.
My SQL statement is as such:
Select pk from usersDates order by datetime(usersDate, 'localtime') ASC
I have dates stored in the database which range as far as 2111. However the order the data is returned in indicates that dates from 2036 happen after the ones from 2111.
The column 'usersDate is actually a double (time interval since 1970 / unix time) - hence the reason for the cast.
Does anyone know what would cause this?
You should re-read the date and time syntax. The 'localtime' modifier expects an UTC time on its left.
Use SELECT pk FROM usersDates ORDER BY datetime(usersDate, 'unixepoch', 'localtime') ASC.

How to store and get datetime value in SQLite

My table contains Birthdate field which has datatype as datetime.
I want to get all records having birthday today.
How can I get it?
Try this query:
SELECT * FROM mytable
WHERE strftime('%m-%d', 'now') = strftime('%m-%d', birthday)
Having a special datetime type has always seemed like unnecessary overhead to me, integers are fast, flexible, and use less space.
For general datetime values use Unix Epoch timestamps. Easy to work with, extremely flexible, as well as timezone (and even calender!) agnostic. (I recently wrote an article on using them, which I really have to plug...)
That said, if you're only interested in dates in the Gregorian calendar you may want to use a large integer in the following format: YYYYMMDD, eg 19761203. For you particular usage you could even create a four digit integer like MMDD, say 1703 — that's got to result in fast selects!
SQLite has very poor support for storing dates. You can use the method suggested by Nick D above but bear in mind that this query will result in full table scan since dates are not indexed correctly in SQLite (actually SQLite does not support dates as a built-in type at all).
If you really want to do a fast query then you'll have to add a separate (integral) column for storing the birth day (1-31) and attach an index for it in the database.
If you only want to compare dates then you can add a single (INTEGER) column that will store the date UTC value (but this trick won't allow you to search for individual date components easily).
Good Luck

Resources