3

I have created a python notebook in Databricks, I have python logic and need to execute a %sql commandlet.

Say I wanted to execute that commandlet2 based on a python variable

cmd1

EXECUTE_SQL= True

cmd2

if condition : 
  %sql .....
1
  • 1
    Since you are using Databricks,it allows you used Sql commands using sql("<query>") Commented Aug 6, 2022 at 7:28

2 Answers 2

3

As mentioned, you can use following Python code (or Scala) to make behavior similar to the %sql cell:

if condition:
  display(spark.sql("your-query"))

One advantage of this approach is that you can embed variables into the query text.

Sign up to request clarification or add additional context in comments.

Comments

0

Another alternate which I used is

  • Extracted the sql to a different notebook,
    • In my case i don't want any results back
    • Also I am cleaning up the delta tables and deleting contents.

/clean-deltatable-notebook (an sql notebook)

delete from <database>.<table>
  • used the dbutils.run.notebook() from the python notebook.

cmd2

if condition :
   result = dbutils.run.notebook('<path-of-(clean-deltatable-noetbook)',timeout_seconds = 30)
   print(result)

Link on dbutils.notebook.run() from Databricks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.