4

Table:

CREATE TABLE logaction
(
  actype varchar(8) not null,
  actime DATETIME not null,
  devid int not null
);

SQL:

insert into logaction values ('TEST', '2013-08-22', 1);
insert into logaction values ('TEST', '2013-08-22 09:45:30', 1);
insert into logaction values ('TEST', 'xyz', 2); // shouldn't this fail?

The last record does make it into the table regardless of the non-datetime value for the actime column. Why and how can I enforce that only good data go in?

Here is a SQL Fiddle.

3 Answers 3

7

Well, there's just no DATETIME type in Sqlite...

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich 
on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. 

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

see doc

You could have created your table like that, it wouldn't have changed anything.

CREATE TABLE logaction
(
  actype varchar(8) not null,
  actime NonexistingType not null,
  devid int not null
);
Sign up to request clarification or add additional context in comments.

2 Comments

do you know how many bits the INTEGER supports ? e.g. can i just put miliseconds from 1/1/1970? i need precise timestamps
i just tested putting 1377181566303 in and it worked so it is all good.
3

Unfortunately, not really in sqlite - it doesn't have a datetime type - see section 1.2 in here

Comments

3

Here's a simple work around:

CREATE TABLE logaction
(
  actype varchar(8) not null,
  actime DATETIME not null check( DATETIME(actime) is not null ),
  devid int not null
);

sqlite> insert into logaction values ('TEST', '2013-08-22', 1);
sqlite> insert into logaction values ('TEST', '2013-08-22 09:45:30', 1);
sqlite> insert into logaction values ('TEST', 'xyz', 2);
Error: constraint failed
sqlite>

3 Comments

yes but will this enable me to query and compare the actime column as a time and not a string ?
@amphibient you'll have to use date and time functions (sqlite.org/lang_datefunc.html) for any date/time comparison
@amphibient This is just a constraint, it won't make it a true DATETIME type.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.