1

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!

2 Answers 2

1

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
3
  • thanks! I saw VIEW in my book, but didn't realize it was the only option (adding a column seems so basic). Is this scalable? I have 4million rows. Should go through the add table, drop table hoops? That also seemed like a hassle with 36 columns. Dec 23, 2010 at 21:21
  • Yes, it's scalable. CREATE VIEW takes O(1) time. It doesn't perform any calculations until you SELECT from the VIEW.
    – dan04
    Dec 23, 2010 at 21:29
  • But with every select, it calculates, then? So it's more convenient, but it isn't helping me calculate a value just once, then? Dec 23, 2010 at 21:39
1

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.

1
  • I am OK with the date and time functions in SQLite. My book explains those pretty well. 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? Dec 23, 2010 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.