AndyP
AndyP

Reputation: 607

Declare variables in redshift and use it in the select query

I am trying to declare variables and use it in my sql query as shown below but it gives me error:

-- this will get the the timestamp in seconds
DECLARE @startTimeStamp bigint = cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)
DECLARE @endTimeStamp bigint = cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-10 16:22:17.897' ) as bigint)

-- my query.
SELECT processId,
houroftheday,
minuteofhour,
listagg(clientId, ',') within group (order by minuteofhour) as clientIds,
count(*) as psg
FROM data.process
where kite = 'BULLS'
and code is null
and timestampinepochsecond >= @startTimeStamp  AND  timestampinepochsecond < @endTimeStamp
group by 1, 2, 3

I read it here as it isn't possible so how can I rewrite my above query so that it can work fine? I tried their example but having issues in converting it out.

Below is what I have tried but I get syntax error:

CREATE TEMP TABLE tmp_variables AS SELECT 
   cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint) AS StartDate, 
   cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-10 16:22:17.897' ) as bigint)      AS EndDate;

Here is my demo where it gives the error:

Upvotes: 1

Views: 4792

Answers (1)

Bill Weiner
Bill Weiner

Reputation: 11032

So Redshift is not exactly Postgres and Postgres does not have DATEDIFF so your dbfiddle example doesn't help. I ran the code you provided on Redshift and got the following error message:

[Amazon](500310) Invalid operation: function pg_catalog.date_diff(character varying, character varying, character varying) does not exist;

This basically lays out the issue '1970-01-01 00:00:00.000' is not a time stamp, it's a text string. This needs to be cast to timestamp for use by DATEDIFF.

DATEDIFF returns a bigint so casting to bigint is not needed.

Also, there is already a builtin function to get the seconds since epoch (1/1/1970) - DATEPART(). Like this:

date_part(epoch, '2016-12-09 16:22:17.897'::timestamp)

Now DATEPART returns a DOUBLE data type so you may want to cast this it BIGINT if you don't want the sub-second information.

If you like your style it will work like this:

CREATE TEMP TABLE tmp_variables AS SELECT 
   cast(DATEDIFF(s, '1970-01-01 00:00:00.000'::timestamp, '2016-12-09 16:22:17.897'::timestamp ) as bigint) AS StartDate, 
   cast(DATEDIFF(s, '1970-01-01 00:00:00.000'::timestamp, '2016-12-10 16:22:17.897'::timestamp ) as bigint)      AS EndDate,
   5556::BIGINT       AS some_id;

Upvotes: 1

Related Questions