Home / Databricks on Azure

Databricks on AzureHow-toIntermediate

Run Databricks SQL from scripts with the Statement Execution API: auth, waits, parameters, large results and cancel

Run SQL on a Databricks SQL warehouse from a script, pipeline or app over REST - Entra ID auth, sync vs async waits, safe parameters, results over 25 MiB and cancelling stuck statements.

Deepak Bhardwaj8 min read

Applies toAzure Databricks SQL warehouses (serverless, pro, classic), Statement Execution API 2.0, Databricks CLI, Databricks SDK for Python, Azure CLI

Goal

You need to run SQL against a Databricks SQL warehouse from somewhere that is not a notebook: an Azure DevOps or GitHub Actions step, an Azure Function, a PowerShell runbook, or a small internal app. You don't want to install an ODBC/JDBC driver. You want a clear success or failure, and the script should not hang.

The Statement Execution API (/api/2.0/sql/statements) covers this. You send a statement, wait a bounded time for it, read the result inline or through download links, and cancel it if needed.

Before you start

Need How to check
A running or auto-starting SQL warehouse databricks warehouses list
Warehouse ID the id column from the command above, or the warehouse's Connection details tab
Caller has CAN USE on the warehouse warehouse Permissions in the UI
Caller has Unity Catalog grants on the objects SHOW GRANTS ON TABLE main.sales.orders
Network path to the workspace URL curl -sI https://adb-<id>.<n>.azuredatabricks.net

Use a service principal for automation, not a person's token. Users leave and tokens expire.

Step 1: get a token

On Azure you can use a Microsoft Entra ID token for the Azure Databricks resource. 2ff814a6-3304-4ab8-85cb-cd0e6f879c1d is the fixed application ID of Azure Databricks:

az login --service-principal -u "$ARM_CLIENT_ID" --tenant "$ARM_TENANT_ID" \
  --federated-token "$(cat $AZURE_FEDERATED_TOKEN_FILE)"   # or -p <secret>

export DATABRICKS_HOST="https://adb-1234567890123456.7.azuredatabricks.net"
export DATABRICKS_TOKEN=$(az account get-access-token \
  --resource 2ff814a6-3304-4ab8-85cb-cd0e6f879c1d \
  --query accessToken -o tsv)

The service principal must be added to the workspace. Otherwise every call returns 401 or 403, whatever its Azure RBAC roles are.

Tip

If you already use the Databricks CLI or SDK with azure-client-id/azure-client-secret or OIDC in a config profile, skip the manual token. Both clients fetch and refresh tokens for you.

Step 2: run a statement and wait

The key settings are wait_timeout and on_wait_timeout:

Setting Behaviour
wait_timeout: "0s" Returns at once with a statement_id. You poll.
wait_timeout: "5s"–"50s" Waits up to that long. If the statement finishes in time, the result is in the response. The default is 10s.
on_wait_timeout: "CONTINUE" (default) After the wait, the statement keeps running and you poll for it.
on_wait_timeout: "CANCEL" After the wait, the statement is cancelled. Use this for "answer quickly or fail" checks.

A short query with a synchronous wait:

curl -s -X POST "$DATABRICKS_HOST/api/2.0/sql/statements" \
  -H "Authorization: Bearer $DATABRICKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
        "warehouse_id": "<warehouse-id>",
        "catalog": "main",
        "schema": "sales",
        "statement": "SELECT count(*) AS n FROM orders WHERE order_date = current_date()",
        "wait_timeout": "30s",
        "on_wait_timeout": "CONTINUE"
      }' | jq '{id: .statement_id, state: .status.state, rows: .result.data_array}'

The same call from the Databricks CLI, which handles auth:

databricks api post /api/2.0/sql/statements --json '{
  "warehouse_id": "<warehouse-id>",
  "statement": "SELECT current_user(), current_catalog()",
  "wait_timeout": "30s"
}'

status.state is one of PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED or CLOSED. Your script should exit non-zero on anything except SUCCEEDED. On FAILED, print status.error.error_code and status.error.message.

Warning

A warehouse that is stopped has to start first. That can take longer than any wait_timeout, so the first call often comes back PENDING. Don't treat PENDING as a failure. Poll, or warm up the warehouse in an earlier pipeline step.

Step 3: poll long statements without hanging

For MERGE, OPTIMIZE or other long DML, submit with "wait_timeout": "0s" and poll with a hard deadline. In Python with the Databricks SDK:

import sys, time
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.sql import StatementState

w = WorkspaceClient()          # reads DATABRICKS_HOST and auth from env or profile
WAREHOUSE_ID = "<warehouse-id>"
DEADLINE_S = 3600

resp = w.statement_execution.execute_statement(
    warehouse_id=WAREHOUSE_ID,
    statement="MERGE INTO main.sales.orders t USING main.staging.orders s "
              "ON t.order_id = s.order_id "
              "WHEN MATCHED THEN UPDATE SET * WHEN NOT MATCHED THEN INSERT *",
    wait_timeout="0s",
)
sid = resp.statement_id
start = time.time()
terminal = {StatementState.SUCCEEDED, StatementState.FAILED,
            StatementState.CANCELED, StatementState.CLOSED}

while True:
    st = w.statement_execution.get_statement(sid)
    if st.status.state in terminal:
        break
    if time.time() - start > DEADLINE_S:
        w.statement_execution.cancel_execution(sid)
        sys.exit(f"Cancelled {sid} after {DEADLINE_S}s")
    time.sleep(10)

if st.status.state != StatementState.SUCCEEDED:
    err = st.status.error
    sys.exit(f"{st.status.state.value}: {err.error_code if err else ''} {err.message if err else ''}")
print("OK", sid)

Always log the statement_id. It's the key for finding the run in Query History and in system.query.history (column statement_id) when someone asks what the pipeline ran.

To cancel from a shell, for example from a CI "cancel" hook:

databricks api post /api/2.0/sql/statements/<statement-id>/cancel

Caution

Cancelling a statement doesn't roll back work that has already committed. A multi-statement script that you send one call at a time can leave the first tables updated and the later ones not. Make each step idempotent (MERGE, or INSERT OVERWRITE of a partition) so that a rerun is safe.

Step 4: pass values as parameters, not string concatenation

Use named parameter markers. They stop SQL injection from pipeline variables and they handle quoting and types:

{
  "warehouse_id": "<warehouse-id>",
  "statement": "DELETE FROM main.sales.orders WHERE region = :region AND order_date < :cutoff",
  "parameters": [
    { "name": "region", "value": "EMEA" },
    { "name": "cutoff", "value": "2026-01-01", "type": "DATE" }
  ],
  "wait_timeout": "30s"
}

If you leave out type, the value is a STRING. Parameter markers replace values only. They can't replace table or column names. For a dynamic table name, use IDENTIFIER(:table_name) in the statement.

Step 5: results larger than a few rows

Disposition Format Limit Use for
INLINE (default) JSON_ARRAY only about 25 MiB; larger results fail counts, checks, small lookups
EXTERNAL_LINKS JSON_ARRAY, ARROW_STREAM, CSV up to 100 GiB by default (byte_limit) exports and extracts

You can also cap output with row_limit, which is useful for data-quality checks that need only the first few bad rows.

With EXTERNAL_LINKS the result arrives in chunks. Each chunk is a short-lived pre-signed URL to storage:

from databricks.sdk.service.sql import Disposition, Format
import requests

r = w.statement_execution.execute_statement(
    warehouse_id=WAREHOUSE_ID,
    statement="SELECT * FROM main.sales.orders WHERE order_date >= '2026-11-01'",
    disposition=Disposition.EXTERNAL_LINKS,
    format=Format.CSV,
    wait_timeout="50s",
)
# if not finished yet, poll as in Step 3 until SUCCEEDED, then re-read it:
st = w.statement_execution.get_statement(r.statement_id)
total = st.manifest.total_chunk_count
with open("orders.csv", "wb") as out:
    for i in range(total):
        chunk = w.statement_execution.get_statement_result_chunk_n(r.statement_id, i)
        for link in chunk.external_links:
            out.write(requests.get(link.external_link, timeout=300).content)  # no auth header

Rules for external links:

  • Don't send the Databricks Authorization header to the link URL. The URL already carries its own credentials, and the storage service rejects the extra header.
  • Links expire (see the expiration field). Download right away. Don't store the links.
  • Treat the links as secrets. Anyone who has one can download that chunk until it expires.
  • With CSV, each chunk may contain its own header row. Check this on your build before you concatenate files for a downstream loader.

Troubleshooting

Symptom Likely cause Fix
401/403 on the POST token for the wrong resource, or the service principal isn't in the workspace use resource 2ff814a6-..., add the service principal to the workspace
PERMISSION_DENIED ... warehouse no CAN USE on the warehouse grant CAN USE to the service principal or its group
FAILED with TABLE_OR_VIEW_NOT_FOUND wrong default catalog/schema set catalog/schema in the request or use three-part names
State stays PENDING warehouse starting, or queue full at max clusters check warehouse state; raise max clusters or warm up first
Inline result fails on size result over the inline limit switch to EXTERNAL_LINKS or add row_limit
External link download returns 403 or times out Authorization header sent, link expired, or workspace storage firewall blocks the client drop the header, download at once, allow the client network on the workspace storage account
State CLOSED when fetching later result already expired or closed fetch results right after SUCCEEDED

The external-link storage path is the same one Cloud Fetch uses. If BI tools already fail on large results, see the Cloud Fetch and workspace storage firewall post for the network side.

Prevent it next time

  • Use one service principal per pipeline, with CAN USE only on the warehouse it needs and the narrowest Unity Catalog grants.
  • Always set a client-side deadline and cancel on timeout. Also set STATEMENT_TIMEOUT on the warehouse as a server-side backstop.
  • Log statement_id, warehouse ID and duration for every call so you can trace failures in system.query.history.
  • Use INLINE for checks and EXTERNAL_LINKS for anything you export. Never build SQL by string concatenation.
  • Keep long SQL in versioned files in your repo, and send it with parameters, rather than embedding it in YAML.