Sub topic 16
Running SQL on a warehouse from code
This chapter assumes you can run queries in the SQL editor, you know what a SQL warehouse is, and you have a personal access token or other credential for your workspace. It also assumes you have read the earlier chapters on warehouse permissions and the catalog.schema.table namespace. Here you will send the same kind of query from a script and handle the result.
Why run SQL from code
The SQL editor suits exploration. Code suits anything that must run without you: a nightly export, a web service that reads a table, or a test that checks a row count. In all of these, your code is a client and the warehouse does the work. The warehouse does not change. It still starts, scales, queues, and bills as before, and the statement still appears in query history.
There are two common ways to send SQL:
| Approach | What it is | Best for |
|---|---|---|
| Statement Execution API | An HTTP REST API at `/api/2.0/sql/statements` | Any language, serverless functions, short-lived jobs, no driver to install |
| Databricks SQL connector (Python, Node.js, Go, JDBC, ODBC) | A driver that keeps a session and a cursor | Applications that run many queries, BI tools, DB-API style code |
The rest of this chapter focuses on the REST API, then shows the Python connector for comparison.
What you need before the first call
Every call needs three values.
- Workspace URL. For example
https://adb-1234567890123456.7.azuredatabricks.net. Store it inDATABRICKS_HOST. - Credential. A personal access token or an OAuth token for a user or service principal. Store it in
DATABRICKS_TOKEN. - Warehouse ID. Find it on the warehouse's Connection details tab. Store it in
WAREHOUSE_ID.
The identity behind the token needs CAN USE on the warehouse and the Unity Catalog privileges on the data (USE CATALOG, USE SCHEMA, SELECT). Without them the call fails, even though the same query works for you in the editor.
The request and response flow
A statement runs asynchronously. You submit it, and the API either returns the result immediately or returns a handle that you poll.
Submitting a statement
This request, from the chapter's example set, sends a count query to one warehouse and waits up to 30 seconds.
curl -X POST "$DATABRICKS_HOST/api/2.0/sql/statements" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"warehouse_id": "'"$WAREHOUSE_ID"'",
"statement": "SELECT COUNT(*) FROM samples.nyctaxi.trips",
"wait_timeout": "30s"
}'The main request fields are:
warehouse_id: which warehouse runs the statement. Required.statement: the SQL text. Required.wait_timeout: how long the call blocks. Use0sto return at once, or a value from5sto50s. The default is10s.on_wait_timeout:CONTINUE(the default) keeps the statement running after the timeout.CANCELcancels it.catalogandschema: defaults for unqualified names. You can still use full three-level names.row_limitandbyte_limit: caps on the result size.parameters: values for named markers, described below.
The response contains a statement_id and a status.state. The states are PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED, and CLOSED. When the state is SUCCEEDED, manifest.schema.columns describes the columns and result.data_array holds the rows.
Polling in Python
The script below submits a statement, polls until a final state, and turns the rows into dictionaries. It needs only the requests package.
import os
import time
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/")
headers = {"Authorization": f"Bearer {os.environ['DATABRICKS_TOKEN']}"}
body = {
"warehouse_id": os.environ["WAREHOUSE_ID"],
"statement": (
"SELECT pickup_zip, COUNT(*) AS trips "
"FROM samples.nyctaxi.trips "
"GROUP BY pickup_zip ORDER BY trips DESC LIMIT 5"
),
"wait_timeout": "10s",
"on_wait_timeout": "CONTINUE",
}
resp = requests.post(f"{host}/api/2.0/sql/statements",
headers=headers, json=body, timeout=60)
resp.raise_for_status()
payload = resp.json()
statement_id = payload["statement_id"]
while payload["status"]["state"] in ("PENDING", "RUNNING"):
time.sleep(2)
poll = requests.get(f"{host}/api/2.0/sql/statements/{statement_id}",
headers=headers, timeout=60)
poll.raise_for_status()
payload = poll.json()
state = payload["status"]["state"]
if state != "SUCCEEDED":
error = payload["status"].get("error", {})
raise RuntimeError(f"Statement {statement_id} ended as {state}: {error}")
columns = [c["name"] for c in payload["manifest"]["schema"]["columns"]]
for row in payload["result"]["data_array"]:
print(dict(zip(columns, row)))Two points about this code. First, raise_for_status() catches HTTP-level problems such as a bad token, while the state check catches SQL-level problems such as a missing table. A request can succeed over HTTP and still report FAILED. Second, in the default JSON format every value in data_array arrives as a string (or null), so convert numbers and dates yourself using the type names in the manifest.
Parameters instead of string building
Do not build SQL by pasting user input into a string. That invites SQL injection. Use named markers, the same :name syntax as the editor's query parameters, and pass values in parameters.
curl -X POST "$DATABRICKS_HOST/api/2.0/sql/statements" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"warehouse_id": "'"$WAREHOUSE_ID"'",
"statement": "SELECT pickup_zip, trip_distance, fare_amount FROM samples.nyctaxi.trips WHERE trip_distance > :min_distance ORDER BY fare_amount DESC LIMIT 50",
"parameters": [
{ "name": "min_distance", "value": "5", "type": "DOUBLE" }
],
"wait_timeout": "30s"
}'Each parameter has a name, a string value, and an optional SQL type. If you omit type, it defaults to STRING. Declare a numeric type for numeric comparisons.
Large results
Inline results ("disposition": "INLINE", the default) suit small answers. The inline limit is about 25 MiB. For bigger results, set "disposition": "EXTERNAL_LINKS". The response then lists chunks, each with a short-lived pre-signed URL that you download directly from cloud storage, without sending your Databricks token to that URL. You can pair this with "format": "ARROW_STREAM" or CSV for faster bulk reads. Large inline results can also be split into chunks, which you fetch with GET /api/2.0/sql/statements/{statement_id}/result/chunks/{chunk_index}.
Cancelling and expiry
To stop a running statement, send POST /api/2.0/sql/statements/{statement_id}/cancel. Results are kept only for a limited time after the statement finishes, and fetching them after they expire returns an error. Read the data promptly, and write to a table if you need it to persist.
The Python connector for comparison
If your application issues many queries, a driver is usually simpler. The databricks-sql-connector package handles polling, result fetching, and session reuse.
import os
from databricks import sql
with sql.connect(
server_hostname=os.environ["DATABRICKS_HOST"].replace("https://", ""),
http_path=os.environ["DATABRICKS_HTTP_PATH"],
access_token=os.environ["DATABRICKS_TOKEN"],
) as connection:
with connection.cursor() as cursor:
cursor.execute(
"SELECT pickup_zip, fare_amount "
"FROM samples.nyctaxi.trips "
"WHERE trip_distance > :min_distance LIMIT 10",
{"min_distance": 5},
)
for row in cursor.fetchall():
print(row)The http_path value also comes from the warehouse's Connection details tab. Recent versions of the connector use native named parameters, as shown. Older versions use a different, client-side parameter style, so check the version you have installed.
Common errors
- 401 or 403 on submit. The token is invalid, or the identity lacks
CAN USEon the warehouse. - State
FAILEDwith a permission message. The identity lacks a Unity Catalog privilege. Check it with the same user in the editor. INVALID_PARAMETER_VALUEonwait_timeout. The value is outside0sor5sto50s.- State stuck at
PENDING. The warehouse is starting, or it has reached its maximum cluster count and is queueing statements. Check the warehouse monitoring tab. - Numbers compare as text. You left out the parameter
typeor forgot to convert the string results.
Exercise
Your script posts a statement with "waittimeout": "5s" to a stopped pro warehouse. The response has state PENDING and a statementid. What should the script do next, and why should it not simply post the statement again?
Show answer
It should poll GET /api/2.0/sql/statements/{statementid} until the state is SUCCEEDED, FAILED, or CANCELED. With the default onwait_timeout of CONTINUE, the original statement is still queued while the warehouse starts. Posting it again would run the query twice, which wastes compute and can repeat side effects such as an INSERT.
Exercise
A report script builds its SQL as f"... WHERE city = '{city}'" using text typed by a user. Rewrite the request body fields so the value travels safely, and name the field that sets its type.
Show answer
Use the statement "... WHERE city = :city" and add "parameters": [{"name": "city", "value": "<user text>", "type": "STRING"}]. The type field sets the SQL type. The value is bound as data and is never parsed as SQL, which prevents injection.