# Execute a SQL statement

Launch stage: Public Preview

`POST /api/2.0/sql/warehouses/{warehouse_id}/statements`

Execute a SQL statement and optionally await its results for a specified time.

 **Use case: small result sets with INLINE + JSON_ARRAY**

 For flows that generate small and predictable result sets (<= 25 MiB), `INLINE` responses of `JSON_ARRAY` result
 data are typically the simplest way to execute and fetch result data.

 **Use case: large result sets with EXTERNAL_LINKS**

 Using `EXTERNAL_LINKS` to fetch result data allows you to fetch large result sets efficiently.
 The main differences from using `INLINE` disposition are that the result data is accessed
 with short-lived cloud-storage URLs, and
 that there are 3 supported formats: `JSON_ARRAY`, `ARROW_STREAM` and `CSV` compared to only `JSON_ARRAY` with
 `INLINE`.

 **External-link URLs**

 External links point to data stored within your workspace's internal cloud storage. The URLs are valid for only a
 short period, <= 15 minutes. Alongside each `external_link` is an expiration field indicating the time at which the URL
 is no longer valid. In `EXTERNAL_LINKS` mode, chunks can be resolved and fetched multiple times and in parallel.

 ----

 ### **Warning: Databricks strongly recommends that you protect the URLs that are returned by the `EXTERNAL_LINKS` disposition.**

 When you use the `EXTERNAL_LINKS` disposition, a short-lived cloud-storage URL is generated to download the
 results. The URL contains temporary access credentials, so protect it and do not set an `Authorization` header in
 the download request.

 
 
 

 The `EXTERNAL_LINKS` disposition can be disabled upon request by creating a [support case](https://docs.databricks.com/resources/support.html).

 See also [Security best practices](https://docs.databricks.com/sql/admin/sql-execution-tutorial.html#security-best-practices).

 ----

 StatementResponse contains `statement_id` and `status`; other fields might be absent or present depending on
 context. If the SQL warehouse fails to execute the provided statement, a 200 response is returned with
 `status.state` set to `FAILED` (in contrast to a failure when accepting the request, which results in a non-200
 response). Details of the error can be found at `status.error` in case of execution failures.

API scopes: sql

**AWS**

On AWS, external links are presigned URLs for Amazon S3.

**Azure**

On Azure, external links are SAS URLs for Azure Storage.

**GCP**

On GCP, external links are signed URLs for Google Cloud Storage.

## Path parameters

- `warehouse_id` (string, required)
  The ID of the SQL warehouse to run the statement on. Currently, only
   [Lakehouse//RT](https://docs.databricks.com/compute/sql-warehouse/real-time.html) warehouses are supported. See also
   [What are SQL warehouses?](https://docs.databricks.com/sql/admin/warehouse-type.html).

## Request body

- `statement` (string, required)
  The SQL statement to execute. The statement can optionally be parameterized, see `parameters`.
   The maximum query text size is 16 MiB.
  Example: `SELECT * FROM range(10)`
- `catalog` (string, optional)
  Sets default catalog for statement execution, similar to
   [`USE CATALOG`](https://docs.databricks.com/sql/language-manual/sql-ref-syntax-ddl-use-catalog.html)
   in SQL.
- `schema` (string, optional)
  Sets default schema for statement execution, similar to
   [`USE SCHEMA`](https://docs.databricks.com/sql/language-manual/sql-ref-syntax-ddl-use-schema.html)
   in SQL.
- `row_limit` (int64, optional)
  Applies the given row limit to the statement's result set, but unlike the `LIMIT` clause in SQL,
    it also sets the `truncated` field in the response to indicate whether the result was trimmed due to the limit or
    not.
- `byte_limit` (int64, optional)
  Applies the given byte limit to the statement's result size. Byte counts are based on internal data
    representations and might not match the final size in the requested `format`. If the result was truncated due to
    the byte limit, then `truncated` in the response is set to `true`.
    When using `EXTERNAL_LINKS` disposition, a default `byte_limit` of 100 GiB is applied if `byte_limit` is not
    explicitly set.
- `format` (string, optional)
  Statement execution supports three result formats: `JSON_ARRAY`, `ARROW_STREAM`, and `CSV`. Set `format`
   explicitly: on Lakehouse//RT warehouses, an omitted `format` with the `INLINE` disposition currently returns
   Arrow data rather than `JSON_ARRAY`.
  
   Important: The formats `ARROW_STREAM` and `CSV` are supported only with `EXTERNAL_LINKS` disposition.
   `JSON_ARRAY` is supported in `INLINE` and `EXTERNAL_LINKS` disposition.
  
   When specifying `format=JSON_ARRAY`, result data will be formatted as an array of arrays of values, where each
   value is either the *string representation* of a value, or `null`.
   For example, the output of `SELECT concat('id-', id) AS strCol, id AS intCol, null AS nullCol FROM range(3)` would
   look like this:
  
   ```
    [
    [ "id-1", "1", null ],
    [ "id-2", "2", null ],
    [ "id-3", "3", null ],
    ]
   ```
  
   When specifying `format=JSON_ARRAY` and `disposition=EXTERNAL_LINKS`, each chunk in the result contains compact
   JSON with no indentation or extra whitespace.
  
   When specifying `format=ARROW_STREAM` and `disposition=EXTERNAL_LINKS`, each chunk in the result will be formatted
   as Apache Arrow Stream. See the
   [Apache Arrow streaming format](https://arrow.apache.org/docs/format/Columnar.html#ipc-streaming-format).
  
   When specifying `format=CSV` and `disposition=EXTERNAL_LINKS`, each chunk in the result will be a CSV according to
   [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180) standard.
   All column values will have *string representation* similar to the `JSON_ARRAY` format, and `null` values will
   be encoded as “null”.
   Only the first chunk in the result would contain a header row with column names.
   For example, the output of `SELECT concat('id-', id) AS strCol, id AS intCol, null as nullCol FROM range(3)` would
   look like this:
  
   ```
   strCol,intCol,nullCol
   id-1,1,null
   id-2,2,null
   id-3,3,null
   ```
  Possible values:
  - `JSON_ARRAY`
  - `ARROW_STREAM`
  - `CSV`
- `disposition` (string, optional)
  The fetch disposition provides two modes of fetching results: `INLINE` and `EXTERNAL_LINKS`.
  
    Statements executed with `INLINE` disposition will return result data inline, in `JSON_ARRAY` format, in a series
    of chunks. If a given statement produces a result set with a size larger than 25 MiB,
    that statement execution is aborted, and no result set will be available.
  
    **NOTE**
    Byte limits are computed based upon internal representations of the result set data, and might not match the sizes
    visible in JSON responses.
  
    Statements executed with `EXTERNAL_LINKS` disposition will return result data as external links: URLs that point
    to cloud storage internal to the workspace. Using `EXTERNAL_LINKS` disposition allows statements to generate
    arbitrarily sized result sets for fetching up to 100 GiB. The resulting links have two important properties:
  
    1. They point to resources _external_ to the Databricks compute; therefore any associated authentication
       information (typically a personal access token, OAuth token, or similar) _must be removed_ when fetching from
       these links.
  
    2. These are short-lived cloud-storage URLs
       with a specific expiration, indicated in the response. The behavior when attempting to use an expired link is
       cloud specific.
  **AWS:** On AWS, external links are presigned URLs.
  **Azure:** On Azure, external links are SAS URLs.
  **GCP:** On GCP, external links are signed URLs.
  Possible values:
  - `INLINE`
  - `EXTERNAL_LINKS`
  Default: `INLINE`
- `wait_timeout` (string, optional)
  The time in seconds the call will wait for the statement's result set as `Ns`, where `N` can be set to 0 or to a
   value between 5 and 50.
  
   When set to `0s`, the statement will execute in asynchronous mode and the call will not wait for the execution to
   finish. In this case, the call returns directly with `PENDING` state and a statement ID which can be used for
   polling the statement status.
  
   When set between 5 and 50 seconds, the call will behave synchronously up to this timeout and wait for the statement
   execution to finish. If the execution finishes within this time, the call returns immediately with a manifest and
   result data (or a `FAILED` state in case of an execution error). If the statement takes longer to execute,
   `on_wait_timeout` determines what should happen after the timeout is reached.
  Default: `10s`
- `on_wait_timeout` (string, optional)
  When `wait_timeout > 0s`, the call will block up to the specified time. If the statement execution doesn't
   finish within this time, `on_wait_timeout` determines whether the execution should continue or be canceled.
   When set to `CONTINUE`, the statement execution continues asynchronously and the call returns a statement ID
   which can be used for polling the statement status. When set to `CANCEL`, the statement execution is
   canceled and the call returns with a `CANCELED` state. Lakehouse//RT warehouses currently don't support
   `CANCEL`: the statement keeps running as with `CONTINUE`.
  Possible values:
  - `CONTINUE`
  - `CANCEL`
  Default: `CONTINUE`
- `parameters` (array of object, optional)
  A list of parameters to pass into a SQL statement containing parameter markers. A
   parameter consists of a name, a value, and optionally a type. To represent a NULL
   value, the `value` field may be omitted or set to `null` explicitly. If the `type` field
   is omitted, the value is interpreted as a string.
  
   If the type is given, parameters will be checked for type correctness according
   to the given type. A value is correct if the provided string can be converted to
   the requested type using the `cast` function. The exact semantics are described in
   the section [`cast` function](https://docs.databricks.com/sql/language-manual/functions/cast.html) of the SQL language reference.
  
   For example, the following statement contains two parameters, `my_name` and `my_date`:
  
   ```
       SELECT * FROM my_table WHERE name = :my_name AND date = :my_date
   ```
  
   The parameters can be passed in the request body as follows:
  
   ```
       {
         ...,
         "statement": "SELECT * FROM my_table WHERE name = :my_name AND date = :my_date",
         "parameters": [
           { "name": "my_name", "value": "the name" },
           { "name": "my_date", "value": "2020-01-01", "type": "DATE" }
         ]
       }
   ```
  
   Currently, positional parameters denoted by a `?` marker are not supported by the
   Databricks SQL Statement Execution API.
  
   Also see the section [Parameter markers](https://docs.databricks.com/sql/language-manual/sql-ref-parameter-marker.html) of the SQL language reference.
  - `name` (string, required)
    The name of a parameter marker to be substituted in the statement.
  - `value` (string, optional)
    The value to substitute, represented as a string. If omitted, the value is interpreted as NULL.
  - `type` (string, optional)
    The data type, given as a string. For example: `INT`, `STRING`, `DECIMAL(10,2)`.
     If no type is given the type is assumed to be `STRING`. Complex types, such as
     `ARRAY`, `MAP`, and `STRUCT` are not supported. For valid types, refer to the
     section [Data types](https://docs.databricks.com/sql/language-manual/functions/cast.html) of the SQL language reference.
- `query_tags` (array of object, optional)
  An array of query tags to annotate a SQL statement. A query tag
   	consists of a non-empty key and, optionally, a value. To represent a NULL
   	value, either omit the `value` field or manually set it to `null` or white space.
   	Refer to the SQL language reference for the format specification of query tags.
   	There's no significance to the order of tags. Only one value per key will be recorded.
    A sequence in excess of 20 query tags will be coerced to 20.
    Example:
  
       {
         ...,
         "query_tags": [
           { "key": "team", "value": "eng" },
           { "key": "some key only tag" }
         ]
       }
  - `key` (string, required)
    The key of the tag.
  - `value` (string, optional)
    The value of the tag. Key-only tags have no value.

## Returns

Returns the StatementResponse object.

## Request

### Asynchronous execution

```json
{
  "format": "JSON_ARRAY",
  "statement": "SELECT * FROM range(100)",
  "wait_timeout": "0s"
}
```

### Default (wait up to 10s, fallback to async)

```json
{
  "format": "JSON_ARRAY",
  "statement": "SELECT * FROM range(3)"
}
```

### EXTERNAL_LINKS with ARROW_STREAM

```json
{
  "disposition": "EXTERNAL_LINKS",
  "format": "ARROW_STREAM",
  "statement": "SELECT * FROM range(100)"
}
```

### EXTERNAL_LINKS with CSV

```json
{
  "disposition": "EXTERNAL_LINKS",
  "format": "CSV",
  "statement": "SELECT * FROM range(100)"
}
```

### EXTERNAL_LINKS with JSON_ARRAY

```json
{
  "disposition": "EXTERNAL_LINKS",
  "format": "JSON_ARRAY",
  "statement": "SELECT * FROM range(100)"
}
```

### Named parameters

```json
{
  "format": "JSON_ARRAY",
  "parameters": [
    {
      "name": "my_id",
      "type": "BIGINT",
      "value": "2"
    }
  ],
  "statement": "SELECT id FROM range(10) WHERE id = :my_id"
}
```

### Wait up to 30s, fallback to async

```json
{
  "format": "JSON_ARRAY",
  "on_wait_timeout": "CONTINUE",
  "statement": "SELECT * FROM range(100)",
  "wait_timeout": "30s"
}
```

## Response

### Statement failed with syntax error

```json
{
  "statement_id": "01ee48eb-5124-1922-bb90-f98c82f024fe",
  "status": {
    "error": {
      "error_code": "BAD_REQUEST",
      "message": "[PARSE_SYNTAX_ERROR] Syntax error at or near ..."
    },
    "state": "FAILED"
  }
}
```

### Statement running

```json
{
  "statement_id": "01ed9db9-24c4-1cb6-a320-fb6ebbe7410d",
  "status": {
    "state": "RUNNING"
  }
}
```

### Statement succeeded with EXTERNAL_LINKS and CSV

```json
{
  "manifest": {
    "chunks": [
      {
        "byte_count": 293,
        "chunk_index": 0,
        "row_count": 100,
        "row_offset": 0
      }
    ],
    "format": "CSV",
    "schema": {
      "column_count": 1,
      "columns": [
        {
          "name": "id",
          "position": 0,
          "type_name": "LONG",
          "type_text": "BIGINT"
        }
      ]
    },
    "total_byte_count": 293,
    "total_chunk_count": 1,
    "total_row_count": 100,
    "truncated": false
  },
  "result": {
    "external_links": [
      {
        "byte_count": 293,
        "chunk_index": 0,
        "expiration": "2023-01-30T22:23:23.140Z",
        "external_link": "https://someplace.cloud-provider.com/very/long/path/...",
        "row_count": 100,
        "row_offset": 0
      }
    ]
  },
  "statement_id": "01eda0ea-9b4b-15ce-b8bb-a7d4114cb5ed",
  "status": {
    "state": "SUCCEEDED"
  }
}
```

### Statement succeeded with INLINE data

```json
{
  "manifest": {
    "chunks": [
      {
        "chunk_index": 0,
        "row_count": 3,
        "row_offset": 0
      }
    ],
    "format": "JSON_ARRAY",
    "schema": {
      "column_count": 1,
      "columns": [
        {
          "name": "id",
          "position": 0,
          "type_name": "LONG",
          "type_text": "BIGINT"
        }
      ]
    },
    "total_chunk_count": 1,
    "total_row_count": 3,
    "truncated": false
  },
  "result": {
    "chunk_index": 0,
    "data_array": [
      [
        "0"
      ],
      [
        "1"
      ],
      [
        "2"
      ]
    ],
    "row_count": 3,
    "row_offset": 0
  },
  "statement_id": "01eda0e7-e315-1846-84e2-79a963ffad44",
  "status": {
    "state": "SUCCEEDED"
  }
}
```

