When defining a relation, I want to update an attribute to the timestamp at insert. For example, a working table that I have right now
CREATE TABLE t1(
id INTEGER PRIMARY KEY AUTOINCREMENT,
time TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
txt TEXT);
This is updating a timestamp on insert, for example, insert into t1 (txt) values ('hello') adds the row 1|2012-07-19 08:07:20|hello|. However, I want to have this date formatted in unixepoch format.
I read the docs but this wasn't clear. For example, I modified the table relation to time TIMESTAMP DEFAULT DATETIME('now','unixepoch') but I get an error. Here, as in the docs, now was my time string and unixepoch was the modifier but it didn't work. Could someone help me how to format it as a unixepoch timestamp?
Use strftime:
sqlite> select strftime('%s', 'now');
1342685993
Use it in CREATE TABLE like this:
sqlite> create table t1 (
...> id integer primary key,
...> time timestamp default (strftime('%s', 'now')),
...> txt text);
sqlite> insert into t1 (txt) values ('foo');
sqlite> insert into t1 (txt) values ('bar');
sqlite> insert into t1 (txt) values ('baz');
sqlite> select * from t1;
1|1342686319|foo
2|1342686321|bar
3|1342686323|baz
See https://www.sqlite.org/lang_createtable.html#tablecoldef
If the default value of a column is an expression in parentheses, then the expression is evaluated once for each row inserted and the results used in the new row.
Note 'timestamp' is not a data type known to SQLite (see list here). The default value generated by strftime() would actually be stored as Text.
If it is important to store the value as a number instead of as a string, declare the field as an Integer and add a CAST() into the mix, like so:
create table t1(
...
ts_field integer(4) default (cast(strftime('%s','now') as int)),
...
);
Indeed strftime, which can also be used like so:
SELECT strftime('%s', timestamp) as timestamp FROM ... ;
Gives you:
1454521888
'timestamp' table column can be a text field even, using the current_timestamp as DEFAULT.
Without strftime:
SELECT timestamp FROM ... ;
Gives you:
2016-02-03 17:51:28
Related
I constantly retrieve JSON data from some API and put that data into a MariaDB table.
The JSON ships with a timestamp which I'd like to place an index on, because this attribute is used for querying the table.
The JSON looks something like this (stripped):
{
"time": "2021-12-26T14:00:00.007294Z",
"some_measure": "0.10031"
}
I create a table:
CREATE TABLE some_table (
my_json JSON NOT NULL,
time TIMESTAMP AS (JSON_VALUE(my_json , '$.time')),
some_measure DOUBLE AS (JSON_VALUE(my_json , '$.some_measure'))
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_general_ci;
my_json holds the entire JSON snippet, time and some_measure are virtual columns properly extracting the corresponding JSON values on the fly.
Now, trying to add an index on the TIMESTAMP attribute:
CREATE INDEX some_index ON some_table (time);
This fails:
SQL Error [1292] [22007]: (conn=454) Incorrect datetime value:
'2021-12-26T14:00:00.007294Z' for column `some_db`.`some_table`.`time` at row 1
How can I add an index on that timestamp?
The issue here is that converting a string (the JSON timestamp) to a TIMESTAMP is non-deterministic because it involves server side settings (sql_mode) and timezone settings.
Indexing virtual columns which are non-deterministic is not supported.
You would want to use a VARCHAR data type instead and index that:
CREATE TABLE some_table (
my_json JSON NOT NULL,
time VARCHAR(100) AS (JSON_VALUE(my_json , '$.time')),
some_measure DOUBLE AS (JSON_VALUE(my_json , '$.some_measure'))
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_general_ci;
You should be able to create your index:
CREATE INDEX some_index ON some_table (`time`);
You can still query time because MariaDB automatically converts DATETIMEs if used against a VARCHAR:
SELECT
*
FROM some_table
WHERE time > '2008-12-31 23:59:59' + INTERVAL 1 SECOND;
The query will use the index:
I finally came up with a solution that works for me.
Changes are:
use STR_TO_DATE() to create a valid DATETIME from the JSON timestamp
make the generated (virtual) column PERSISTENT
use data type DATETIME instead of TIMESTAMP
So the new code looks like this:
CREATE TABLE some_table (
my_json JSON NOT NULL,
time DATETIME AS (STR_TO_DATE((JSON_VALUE(my_json , '$.time')), '%Y-%m-%d%#%T%.%#%#')) PERSISTENT,
some_measure DOUBLE AS (JSON_VALUE(my_json , '$.some_measure'))
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_general_ci;
CREATE INDEX some_index ON some_table (`time`);
Can any body tell how to remove or skip the millisecond part while inserting the current time to the timestamp column in Postgres database table. Actually the column that holds the data type timestamp without timezone and default is set to now() i.e. it will take the current date and time.
It inserts right date and time but it puts the millisecond part for example the format that gets entered is "2015-01-07 10:27:44.234534" which has millisecond part i.e 234534 which I don't want to be inserted. I only want the the data that is to be inserted is as "2015-01-07 10:27:44". Can any body let me know without changing the data type of that column how to insert the current date and time skipping the millisecond part.
Change your default to strip off the milliseconds:
create table foo
(
id integer not null primary key,
created_at timestamp default date_trunc('second', current_timestamp)
);
Or to change the default for an existing table:
alter table foo
alter column created_at set default date_trunc('second', current_timestamp);
To change the existing values, you can use:
update foo
set created_at = date_trunc('second', created_at)
where created_at is not null;
Instead of using date_trunc you can also just cast the value: created_at::timestamp(0) for the update statement, or current_timestamp::timestamp(0) in the default value.
As alternative, if you could modify the data type of that column, you could insert by default the CURRENT_TIME:
CREATE TABLE my_table (
col1 TEXT,
col2 INTEGER,
ts TIMESTAMP(0) DEFAULT CURRENT_TIMESTAMP
);
The 0 between parentheses is saying that you don't want any milliseconds. See the documentation for further details.
I have an SQLite database, version 3 and I am using C# to create an application that uses this database.
I want to use a timestamp field in a table for concurrency, but I notice that when I insert a new record, this field is not set, and is null.
For example, in MS SQL Server if I use a timestamp field it is updated by the database and I don't have to set it by myself. Is this possible in SQLite?
Just declare a default value for a field:
CREATE TABLE MyTable(
ID INTEGER PRIMARY KEY,
Name TEXT,
Other STUFF,
Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
However, if your INSERT command explicitly sets this field to NULL, it will be set to NULL.
You can create TIMESTAMP field in table on the SQLite, see this:
CREATE TABLE my_table (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(64),
sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);
INSERT INTO my_table(name, sqltime) VALUES('test1', '2010-05-28T15:36:56.200');
INSERT INTO my_table(name, sqltime) VALUES('test2', '2010-08-28T13:40:02.200');
INSERT INTO my_table(name) VALUES('test3');
This is the result:
SELECT * FROM my_table;
Reading datefunc a working example of automatic datetime completion would be:
sqlite> CREATE TABLE 'test' (
...> 'id' INTEGER PRIMARY KEY,
...> 'dt1' DATETIME NOT NULL DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),
...> 'dt2' DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%S', 'now', 'localtime')),
...> 'dt3' DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now', 'localtime'))
...> );
Let's insert some rows in a way that initiates automatic datetime completion:
sqlite> INSERT INTO 'test' ('id') VALUES (null);
sqlite> INSERT INTO 'test' ('id') VALUES (null);
The stored data clearly shows that the first two are the same but not the third function:
sqlite> SELECT * FROM 'test';
1|2017-09-26 09:10:08|2017-09-26 09:10:08|2017-09-26 09:10:08.053
2|2017-09-26 09:10:56|2017-09-26 09:10:56|2017-09-26 09:10:56.894
Pay attention that SQLite functions are surrounded in parenthesis!
How difficult was this to show it in one example?
Have fun!
you can use triggers. works very well
CREATE TABLE MyTable(
ID INTEGER PRIMARY KEY,
Name TEXT,
Other STUFF,
Timestamp DATETIME);
CREATE TRIGGER insert_Timestamp_Trigger
AFTER INSERT ON MyTable
BEGIN
UPDATE MyTable SET Timestamp =STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;
CREATE TRIGGER update_Timestamp_Trigger
AFTER UPDATE On MyTable
BEGIN
UPDATE MyTable SET Timestamp = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;
To complement answers above...
If you are using EF, adorn the property with Data Annotation [Timestamp], then
go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:
modelBuilder.Entity<YourEntity>()
.Property(b => b.Timestamp)
.ValueGeneratedOnAddOrUpdate()
.IsConcurrencyToken()
.ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");
It will make a default value to every data that will be insert into this table.
you can use the custom datetime by using...
create table noteTable3
(created_at DATETIME DEFAULT (STRFTIME('%d-%m-%Y %H:%M', 'NOW','localtime')),
title text not null, myNotes text not null);
use 'NOW','localtime' to get the current system date else it will show some past or other time in your Database after insertion time in your db.
Thanks You...
If you use the SQLite DB-Browser you can change the default value in this way:
Choose database structure
select the table
modify table
in your column put under 'default value' the value: =(datetime('now','localtime'))
I recommend to make an update of your database before, because a wrong format in the value can lead to problems in the SQLLite Browser.
I am trying to have a column holding the timestamp value whose default value is today + a few days. Could this be done during table creation time?
Yes it can be done as in the following example:
sqlite> create table foo (i int, j text default (datetime('now', '+5 days')));
sqlite> insert into foo (i) values (1);
sqlite> select * from foo;
1|2012-04-11 07:49:04
sqlite> insert into foo (i) values (2);
sqlite> select * from foo;
1|2012-04-11 07:49:04
2|2012-04-11 07:49:14
If you only want to store the date part, use date instead of datetime. Here I use datetime to show that the default expression is evaluated when inserting in the table, not when the table is created.
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);
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
... 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.
CURRENT_TIMESTAMP is a literal-value just like 'mystring'
column-constraint:
literal-value:
you can use the following query for using current date value in your table
create table tablename (date_field_name Created_on default CURRENT_DATE);