2

I'm generating SQL programmatically so that, based on certain parameters, the query that needs to be executed could be different (i.e., tables used, unions, etc). How can I insert a string like this: "select * from table", into a %%sql block? I know that using :variable inserts variable into the %%sql block, but it does so as a string, rather than sql code.

Thomas K
  • 39,200
  • 7
  • 84
  • 86
econgineer
  • 1,117
  • 10
  • 20

2 Answers2

9

The answer was staring me in the face:

query="""
select 
*
from
sometable
"""
%sql $query
econgineer
  • 1,117
  • 10
  • 20
1

If you want to templatize your queries, you can use string.Template:

from string import Template

template = Template("""
SELECT *
FROM my_data
LIMIT $limit
""")

limit_one = template.substitute(limit=1)
limit_two = template.substitute(limit=2)
%sql $limit_one

Source: JupySQL documentation.

Important: If you use this approach, ensure you trust/sanitize the input!

Eduardo
  • 1,383
  • 8
  • 13