Using variables for schema and table names in a Redshift query

387 Views Asked by At

I want to be able to use the variable names in Redshift which refers to my DB Objects (like schema and table names). Something like...

SET my_schema="schema":
SET my_table="table";
SELECT * from @my_schema.@my_table;

But looks like Redshift doesn't have such feature. Is there any workaround possible to achieve this?

1

There are 1 best solutions below

0
Bill Weiner On

There are a few ways you try to attack this. But first trying to use a database engine for functions beyond querying the database is a waste of horsepower and the road to db lock-in. So I'm going to focus on ways to do this before the database.

The most complete way is to use a front-end system that clients connect to and then this system in turn connects to the db. The one I've used in the past is pgbounce-rr which pools connections to the the db but also allow for modifications to the SQL before being sent on. This will do what you want but you will need a computer to perform this work.

If you use Redshift data-api you could put a Lambda function in series which performs the SQL modifications you desire (but make sure you get your API permissions right). However, I expect it is unlikely that you are looking to move to an API access model.

Many benches support variable substitution and simple replacements in the SQL can be done by the bench. However, this is very dependent on which bench you use and having all users' benches configured correctly.

Bottom line - if you want something to modify your SQL do if before it goes to Redshift.