cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Get Started Discussions
Start your journey with Databricks by joining discussions on getting started guides, tutorials, and introductory topics. Connect with beginners and experts alike to kickstart your Databricks experience.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Databricks SQL - Conditional Catalog query

102842
New Contributor II

Hi is there a way we can do

%sql
select * from {{ catalog }}.schema.table

Where `{{ catalog }}` is a template variable extracted/evaluated from either an environment variable, a databricks secret, or somewhere else? (note: not a widget)

 

3 REPLIES 3

Tharun-Kumar
Databricks Employee
Databricks Employee

@102842 

You can first create a variable to extract the value you want. Then you can use python's string formatting to substitute the variable inside the query.

Let's say catalog is the variable name. Then you can perform

command = f"select * from {catalog}.schema.table"
spark.sql(command)

102842
New Contributor II

Sorry should have specify, i don't want to use the `spark.sql` api. I would want to use it on:

%sql
select * from {{ catalog }}.schema.table

Tharun-Kumar
Databricks Employee
Databricks Employee

Hi @102842 

You can use query parameters to perform this - https://docs.databricks.com/sql/user/queries/query-parameters.html

You can define the catalog name as a query parameter. You should declare the catalog name parameter as a drop down list, because if we declare it as a string, it will add single quotes surrounding the value, during the substitution.

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you wonโ€™t want to miss the chance to attend and share knowledge.

If there isnโ€™t a group near you, start one and help create a community that brings people together.

Request a New Group