Add julian date column to an SQLite table - sqlite

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.

Related

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.

SQLite Query For Dates Equals Today

How to make the query to retrieve from database only the records that have the time equals to 'today'. I store my dates as long.
E.g:
DateColumn (The name of my column) and the name of my table is MyTable
1360054701278 (Tuesday, February 5, 2013 8:58:21 AM GMT)
1359795295000 (Saturday, February 2, 2013 8:54:55 AM GMT)
So how should I make the query for this example in order to retrieve the first record (because it is the date equal to today)?
Any suggestion would be appreciated.
Thanks
sorry for not seeing that, your problem were the additional milliseconds saved in your column.
The solution was to remove them by division ;-)
SELECT * FROM MyTable WHERE date(datetime(DateColumn / 1000 , 'unixepoch')) = date('now')
Use a range for fastest query. You want to avoid converting to compare.
SELECT *
FROM My Table
WHERE DateColumn BETWEEN JulianDay('now') AND JulianDay('now','+1 day','-0.001 second')
Note: I just realized your dates are not stored as Julian Dates which SQLite supports natively. The concept is still the same, but you'll need to use your own conversion functions for whatever format you're storing your dates as.

How to format date and time values for 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.

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

SQLite - storing multiple values

how can I store and retrieve in SQLite database multiple values for the same row of the same column?
i.e. I have a product column and another column is stores, where I put in all the stores, where it is possible to get this product:
Product: iLamp;
Stores: River's; McWay; Lonnie's; ...
How can I implement this?
Thank you in advance.
If you're smart, you won't do this. Because when it comes time to figure out which stores stock the item, your queries will be hideously deformed. So will those of your stock control application when they try to insert and delete stores. What you'll end up with is what I like to call SQL gymnastics, spending more and more time trying to do SQL in the most bizarre way, simply due to a bad design choice.
Seriously, store these in different rows in the database, as Codd intended.
It's far easier (and faster in terms of the DBMS grunt) to combine multiple rows into a single semicolon-separated string than to break that string into elements.
A schema such as this would suffice:
Products:
ProdCode integer primary key
ProdDesc varchar(50)
Stores:
StoreCode integer primary key
StoreDesc varchar(50)
StockLevels:
StoreCode integer \
ProdCode integer / primary key
Count integer
like others have mentioned, you could store it as a comma separated string, and then put that in your database, but like ocdecio mentioned, the way you have your tables right now is bad a design. You should consider doing something like adding another table, like a PRODUCT_TO_STORE table that has two columns, one has the key of a product, and the other column has the key to a store. Then there is a relationship between products and stores, and helps normalize your data, which in most cases, is a good thing. Then when you need to find all the stores a product is in you could just perform a query on that PRODUCT_TO_STORE table.
I would use something simple like JSON. However this is bad db design since it is not normalized.
change the schema.
do not store multiple values in the same row's column.
add a new table where the multiple values can be stored in their own rows
bad table deisgn:
parents:
ParentID, values, other columns
good table design:
parent
parentID, other columns
child
parentID, childID, value
Either store as a comma-separated list for each store or add multiple rows one for each pair "Store"-Product".

Resources