Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redshift: creating a table with Timestamp column defaulting to Now()

Tags:

Is there a way to create a table with a timestamp column defaulting to now?

Any of the following succeeds on creation but fails on insertion.

CREATE TABLE MyTable ( device_id         VARCHAR(64) NOT NULL encode lzo, app_id            VARCHAR(150) NOT NULL distkey encode lzo, retrieval_date    TIMESTAMP without time zone default (now() at time zone 'utc') encode lzo ) diststyle key compound sortkey(app_id,device_id); 

Then on insert:

     insert into MyTable (device_id,app_id) values('a','b'); INFO:  Function "timezone(text,timestamp with time zone)" not supported. INFO:  Function "now()" not supported. ERROR:  Specified types or functions (one per INFO message) not supported on Redshift tables. 

I tried other flavors as below but all fail.

a) Tried with now in single quotes 'now' , create succeeded but failed with another error

b) Tried without the timezone, create succeeded, insert failed.

like image 447
isaac.hazan Avatar asked Jan 04 '16 08:01

isaac.hazan


People also ask

How do I change the default value of a column in Redshift?

You can't alter columns with default values. You can't alter columns with UNIQUE, PRIMARY KEY, or FOREIGN KEY. You can't alter columns within a transaction block (BEGIN ... END).

How do I get the current date in Redshift?

GETDATE returns the current date and time in the current session time zone (UTC by default). It returns the start date or time of the current statement, even when it is within a transaction block.

How do you set a date variable in Redshift?

Something like this: CREATE TEMP TABLE tmp_variables AS SELECT '2015-01-01'::DATE AS StartDate, 'some string' AS some_value, 5556::BIGINT AS some_id; SELECT * FROM Orders WHERE OrderDate >= (SELECT StartDate FROM tmp_variables); The temp table will be deleted after the transaction execution.


1 Answers

You can use SYSDATE or GETDATE() to put a current timestamp value. Here is an example.

dev=> create table my_table (id int, created_at datetime default sysdate); CREATE TABLE  dev=> insert into my_table (id) values (1); INSERT 0 1  dev=> select * from my_table;  id |        created_at ----+---------------------------   1 | 2016-01-04 19:07:14.18745 (1 row) 
  • SYSDATE (Oracle Compatibility Function)
    • http://docs.aws.amazon.com/redshift/latest/dg/r_SYSDATE.html
  • GETDATE()
    • http://docs.aws.amazon.com/redshift/latest/dg/r_GETDATE.html
like image 75
Masashi M Avatar answered Sep 28 '22 18:09

Masashi M