How to format date and time values for SQLite? - sqlite

Can't believe I have to ask this here. Even googling didn't help.
I want to do this:
insert into atable (adatefield,atimefield,adatetimefield) values (A,B,C);
adatefield is defined as DATE
atimefield is defined as TIME
adatetimefield is defined as DATETIME
What do I put for A, B and C?
It's nice that it's free but the documentation for SQLite is awful.

A date, time and datetime field will actually all store datetime, it just depends on what you insert into it, and they will all work with date strings.
You can
insert into atable values("2010-11-16","14:12:22","2010-11-16 14:12:22");
or you can actually just insert "2010-11-16 14:12:22" into all the fields and then select them back with:
select date(adatefield), time(atimefield), datetime(adatetimefield) from atable;
If however you want to make sure that the fields only contain exactly a date,time or datetime and you're inserting from variables, then you can
insert into atable values(date(thedate),time(thedate),datetime(thedate));
Sqlites typelessness makes some things really easy, but can confuse or complicate some other things.

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.

Convert integer column to date column using sqlite query

I am using SQLite.
In my database, I have a integer column value like 20050819. I would like to convert this as date column as like 2005-08-19.
I can achieve my requirement when using the function CONVERT(columnName, DATETIME) in MySQL server. But I need the same result in SQLite.
Is this possible in SQLite query?
You basically have to break apart the date:
select printf('%4d-%02.2d-%02.2d',
columnname/10000, columnname%10000/100, columnname%100)
from tablename;
P.S.
If you have the choice, you will be far better off storing the date in ISO standard format ('YYYY-MM-DD') in the database in the first place.

Error with dates when filling a datatable

I am trying to fill a datatable in vb using SQLiteDataAdapter from a SQLITE database. There are 3 fields in the table that contain dates and they appear as either recent dates or "1899-12-30" . The Fill command generates a "String was not recognized as a valid DateTime." error. I cannot find a date entry that does not look valid, except "1899-12-30", is this a valid date?
Any other thoughts would be appreciated.
Brad
The short answer is 'yes'. I built a table with the three possible ways of storing dates, thus:
CREATE TABLE `JustDate` ( `Date_1` INTEGER, `Date_2` TEXT, `Date_3` REAL )
Then I populated each of those fields in one record with the value you suspect.
And then I did a trial query against the fields to see if sqlite would treat them as proper dates.

Add julian date column to an SQLite table

This is easy, but I can't figure it out from the SQLite FAQ and vignette for ALTER TABLE.
I have a date column, but to find a time difference, I need to use julian dates, so I feel like I might as well add a julian date column because I'll be doing this a lot. But I can't figure out how to do it.
I've gone through a bunch of iterations, but I don't think I'm clicking with the SQLite philosophy of the ALTER TABLE and INSERT INTO commands. Thanks!
But I have no idea how to permanently
add a column to a table that is a
function of other columns in that
table. Is this not common usage?
You can't add a calculated column in an SQLite table. But you can do that with a VIEW.
CREATE TABLE TableWithDates (
ID INTEGER PRIMARY KEY,
Iso8601 TEXT
);
CREATE VIEW ViewWithDates AS
SELECT ID, Iso8601, JULIANDAY(Iso8601) AS Julian
FROM TableWithDates;
sqlite> INSERT INTO TableWithDates VALUES (1, CURRENT_TIMESTAMP);
sqlite> SELECT * FROM TableWithDates;
1|2010-12-23 21:13:26
sqlite> SELECT * FROM ViewWithDates;
1|2010-12-23 21:13:26|2455554.3843287
There are no DATE or TIME types in Sqlite. You're free to select what makes sense for you. If it's just timestamps for logging or something, STRING should be ok. If you're going to do datetime comparisons and math (which you are according to the question), INTEGER would be best.
This page discuses built-in functions for use. If you use INTEGER to store seconds since epoch, you can use subtraction to find a time difference.

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