How do I create an updated "date" field using SQLITE 3? - sql

I am writing a program to help me keep track of my day to day life, and I want one of the fields to be a "date" field that will automatically update. What specifically do I do in SQLITE 3? Something like....
create table day_to_day(
date field
miles_ran INTEGER
food_eaten TEXT
)

How about:
CREATE TABLE day_to_day(
id INTEGER PRIMARY KEY AUTOINCREMENT,
t TIMESTAMP DEFAULT CURRENT_TIMESTAMP
miles_ran INTEGER
food_eaten TEXT
);
which would give you a column called t with the type TIMESTAMP, as a alternative you could also use this:
CREATE TABLE day_to_day(
id INTEGER PRIMARY KEY AUTOINCREMENT,
t DATE DEFAULT (datetime('now','localtime')),
miles_ran INTEGER
food_eaten TEXT
);

Maybe you can use this :
CREATE TABLE table_test (
...
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
or
CREATE TABLE table_test (
...
date DATE DEFAULT (datetime('now','localtime')),
);
This is a good reference : sqlite database default time value 'now'

You can read what the docs have to say about it: SQLite datatypes, scroll to section 1.2.
The gist of it is, you can either use TEXT, REAL, or INTEGER, and then use the corresponding Date/Time function to access it.

Related

Formatting the default date and time for HSQLDB

I have been trying to format the date and time in the CREATE command (to apply for cases where user does not enter any value for date/time). According to the manual, there are the TO_DATE and TO_TIMESTAMP format elements. How do I fix my SQL statement?
http://hsqldb.org/doc/guide/builtinfunctions-chapt.html#N142F5
CREATE TABLE test1(
Id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"Date In" DATE DEFAULT TO_TIMESTAMP(CURRENT_DATE, 'DD/MM/YYYY'),
"Time In" TIME DEFAULT TO_TIMESTAMP(CURRENT_TIME,'HH:MM')
);
I tried with TO_CHAR but still return an error.
https://wiki.documentfoundation.org/Faq/Base/HSQLFunctions
DATE, TIMESTAMP or TIME values do not have "a format". They are stored in a binary way and formatted when they are displayed. So you can't apply "a format" to a DATE column. Additionally, calling to_timestamp() on a value that is a date makes no sense. to_timestamp() is used to convert a string (character) value to a date (or timestamp).
Just define both columns without (wrongly) applying a conversion from a string to a timestamp:
CREATE TABLE test1(
Id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"Date In" DATE DEFAULT CURRENT_DATE,
"Time In" TIME DEFAULT CURRENT_TIME
);
Given the name of the two columns, I think it would make more sense to store that in a single timestamp column:
CREATE TABLE test1(
Id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"Date Time In" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Postgres - range for 'time without time zone' and exclude constraint

I have the following table:
create table booking (
identifier integer not null primary key,
room uuid not null,
start_time time without time zone not null,
end_time time without time zone not null
);
I want to create an exclude constraint to enforce that there are no overlapping appointments for the same room.
I tried the following:
alter table booking add constraint overlapping_times
exclude using gist
(
cast(room as text) with =,
period(start_time, end_time) with &&)
);
This has two problems:
Casting room to text is not enough, it gives: ERROR: data type text has no default operator class for access method "gist". I know in v10 there is btree_gist, but I am using v9.5 and v9.6, so I have to manually cast the uuid to a text afaik.
period(...) is wrong, but I have no idea how to construct a range of time without time zone type.
After installing btree_gist, you can do the following:
create type timerange as range (subtype = time);
alter table booking add constraint overlapping_times
exclude using gist
(
(room::text) with =,
timerange(start_time, end_time) with &&
);
If you want an expression in the constraint you need to put that into parentheses. So either (room::text) or (cast(room as text))

Does the Postgres HSTORE() function only operate on text/integer datatypes in 9.5?

When I use the PostgreSQL 9.5 hstore() construction function on a row object in a query, it seems to only return columns in that row that are the text or integer datatypes. I can see that my timestamp and character varying columns are by default omitted from the HSTORE object that comes back.
In PostgreSQL 9.3 constructing a hstore object would include timestamp and character varying columns of the row as well, how can I get this behavior back?
Specifically my table's DDL looks like:
CREATE TABLE public.sessions
(
id integer NOT NULL DEFAULT nextval('sessions_id_seq'::regclass),
session_id character varying(255) NOT NULL,
data text,
created_at timestamp without time zone,
updated_at timestamp without time zone,
CONSTRAINT sessions_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
Below is the output of running a hstore constructor; note that the session_id, created_at, and updated_at columns (keys) do not get added to the hstore even when their values are not null:
select hstore(sessions.*) from sessions limit 1;
hstore
---------------------------------------------------------------
"id"=>"15435216", "data"=>"DjfBv="
(1 row)
No. All columns should be included. Even with NULL values. (I just tested to verify.)
Maybe you are inadvertently using a different table with the same name in a different schema?
Aside: you can simplify to (equivalent):
SELECT hstore(sessions) FROM public.sessions LIMIT 1;
I schema-qualified public.sessions to make sure the right table is used.
I assume you are aware of the role of the schema search path?
How does the search_path influence identifier resolution and the "current schema"

Auto generate primary key as current date time in H2 database

I have to create a table in H2 with primary key in yyyyMMddHHmmssSSS format.So that for every insert it automatically takes current date time in the mentioned format.
CREATE TABLE TEST_TABLE(ID BIGINT DEFAULT CURRENT_TIMESTAMP() PRIMARY KEY, NAME VARCHAR(255));
Problem is CURRENT_TIMESTAMP() format is yyyy-MM-dd HH:mm:ss.SSS.How can I get it in required format.
You can try this in the H2 console:
call formatdatetime(now(),'yyyyMMddHHmmssSSS');
This will give you a properly formatted string. Now you need to convert it to bigint.
call cast(formatdatetime(now(),'yyyyMMddHHmmssSSS') as bigint);
Last step: change your SQL accordingly...
CREATE TABLE TEST_TABLE(
ID BIGINT DEFAULT CAST(FORMATDATETIME(CURRENT_TIMESTAMP(), 'yyyyMMddHHmmssSSS') AS BIGINT) PRIMARY KEY,
NAME VARCHAR(255)
);
Tested on H2 1.3 and 1.4.
Word of caution: please use transactions and space your insertions...

MySQL create time and update time timestamp

I am creating some tables where I want to store the time when a record was created and when it was last updated. I thought I could have two timestamp fields where one would have the value CURRENT_TIMESTAMP and the other would have CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP. But I guess I can't do this because you can have only 1 timestamp field with a default value in a table?
How would you recommend I get and store the two times? Thanks!
A good way to create fields like 'created' and 'updated' is
CREATE TABLE `mytable` (
`id` INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
`created` TIMESTAMP DEFAULT '0000-00-00 00:00:00',
`updated` TIMESTAMP DEFAULT now() ON UPDATE now(),
`myfield` VARCHAR(255)
);
And its necessary to enter nulls into both columns during "insert":
INSERT INTO mytable (created,updated,myfield) VALUES (null,null,'blablabla');
And now, in all updates, the 'updated' field will have a new value with actual date.
UPDATE mytable SET myfield='blablablablu' WHERE myfield='blablabla';
Source : http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql
As of MYSQL version 5.6.5 you can do this using DEFAULT and ON UPDATE. No triggers are needed.
ts_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ts_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
You can have two columns of type timestamp in one table.
The following works for MySQL 5.0
create table t
(
id integer,
created_at timestamp default current_timestamp,
updated_at timestamp
);
I think you are confusing this with SQL Server (where timestamp is not really a "time stamp" and there is indeed a limit on a single "timestamp" column)
Edit: But you will need a trigger to update the update_at column each time the row is changed.
As far as I know, there's no workaround for that restriction. You'll need to manually set (at least) one of the timestamps, the easiest way is just add updated = NOW() to the UPDATE-query.
You'll need two columns: CREATE_TIME and UPDATE_TIME.
You might want to add CREATE_USER and UPDATE_USER.
Perhaps you'd want to have a 1:many relationship with name of column changed, old and new values.
It's all part of change data capture. You could have CDC tables that are updated using triggers.
I would leave the current timestamp the way you suggested and fill in the created_at field with current date on insert.