Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a variable in RedShift

SQL Server has the ability to declare a variable, then call that variable in a query like so:

DECLARE @StartDate date; SET @StartDate = '2015-01-01';  SELECT * FROM Orders WHERE OrderDate >= @StartDate; 

Does this functionality work in Amazon's RedShift? From the documentation, it looks that DECLARE is used solely for cursors. SET looks to be the function I am looking for, but when I attempt to use that, I get an error.

set session StartDate = '2015-01-01';  [Error Code: 500310, SQL State: 42704]  [Amazon](500310) Invalid operation: unrecognized configuration parameter "startdate"; 

Is it possible to do this in RedShift?

like image 378
mikebmassey Avatar asked Jun 13 '15 18:06

mikebmassey


People also ask

Can you declare variables in Redshift?

Variable declarationVariables can use any valid Amazon Redshift data type. For supported data types, see Data types. PL/pgSQL variables can be any Amazon Redshift supported data type, plus RECORD and refcursor . For more information about RECORD , see Record types.

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.

How do I declare a variable in SQL Workbench?

You can define variables within SQL Workbench/J that can be referenced in your SQL statements. This is done through the internal command WbVarDef . WbVarDef myvar=42 defines a variable with the name myvar and the value 42 . If the variable does not exist, it will be created.


2 Answers

Slavik Meltser's answer is great. As a variation on this theme, you can also use a WITH construct:

WITH 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); 
like image 96
Johan Lammens Avatar answered Sep 20 '22 08:09

Johan Lammens


Actually, you can simulate a variable using a temporarily table, create one, set data and you are good to go.

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.
Temp tables are bound per session (connect), therefor cannot be shared across sessions.

like image 28
Slavik Meltser Avatar answered Sep 22 '22 08:09

Slavik Meltser