tags:

views:

250

answers:

2

Is there a way to create a table in sqlite3 that has a datetime column that defaults to 'now'?

The following statement returns a syntax error:

create table tbl1(id int primary key, dt datetime default datetime('now'));

Update: Here's the correct ddl courtesy of Sky Sanders:

create table tbl1(id int primary key, dt datetime default current_timestamp);
+4  A: 

Try this:

create table tbl1(id int primary key, dt datetime default current_timestamp);

Background:

The DEFAULT constraint specifies a default value to use when doing an INSERT. The value may be NULL, a string constant, a number, or a constant expression enclosed in parentheses. The default value may also be one of the special case-independant keywords CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP. If the value is NULL, a string constant or number, it is inserted into the column whenever an INSERT statement that does not specify a value for the column is executed. If the value is CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP, then the current UTC date and/or time is inserted into the columns. For CURRENT_TIME, the format is HH:MM:SS. For CURRENT_DATE, YYYY-MM-DD. The format for CURRENT_TIMESTAMP is "YYYY-MM-DD HH:MM:SS".

From http://www.sqlite.org/lang_createtable.html

Sky Sanders
worked perfectly, thanks!
NobodyMan
@NobodyMan - my pleasure.
Sky Sanders
+1  A: 
... default (datetime(current_timestamp))

The expression following default must be in parentheses. This form is useful if you want to perform date arithmetic using SQLite date and time functions or modifiers.

Doug Currie
Doug, parenth are only required if an expression is involved. The 'current_xxxx' are keywords and act as literal-value. http://www.sqlite.org/syntaxdiagrams.html#column-constraint
Sky Sanders
Sky, yes, isn't that what I said? My point is that if you want more than what the keywords provide, you may use expressions, but the expression must be in parentheses; the create statement in the original question was missing the parentheses.
Doug Currie
There's no reason to write datetime(current_timestamp). Just use current_timestamp.
dan04
Ah, perhaps I should have used a more complicated example, such as default (datetime('now','start of day'))
Doug Currie