> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://help.sigmacomputing.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://help.sigmacomputing.com/_mcp/server.

# Get the SQL query for a workbook element

GET https://api.sigmacomputing.com/v2/workbooks/{workbookId}/elements/{elementId}/query

This endpoint retrieves the SQL query associated with a specific element in a workbook. It allows users to view and understand how the data for that element is being processed and transformed, which is critical for debugging, optimization, and educational purposes.

### Usage notes
- Retrieve the **workbookId** by calling the [/v2/workbooks](https://help.sigmacomputing.com/reference/list-workbooks) endpoint.
- Retrieve the **elementId** for a custom SQL element by calling the [/v2/workbooks/{workbookId}/queries](https://help.sigmacomputing.com/reference/list-workbook-queries) endpoint.

### Usage scenarios
- **Development and debugging:** Provides developers and analysts with the ability to retrieve and review the SQL code behind workbook elements, facilitating troubleshooting and enhancements.
- **Educational insight:** Useful for training purposes or for users learning to understand the impact of various transformations and filters applied within their Sigma workbooks.

### Best practices
- Ensure proper access controls are in place to manage who can view potentially sensitive query information.
- Use this endpoint as part of a regular review process to ensure that all queries are optimized and up to date with current data schemas.

Reference: https://help.sigmacomputing.com/reference/get-element-query

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: sigma-rest-api
  version: 1.0.0
paths:
  /v2/workbooks/{workbookId}/elements/{elementId}/query:
    get:
      operationId: getElementQuery
      summary: Get the SQL query for a workbook element
      description: >-
        This endpoint retrieves the SQL query associated with a specific element
        in a workbook. It allows users to view and understand how the data for
        that element is being processed and transformed, which is critical for
        debugging, optimization, and educational purposes.


        ### Usage notes

        - Retrieve the **workbookId** by calling the
        [/v2/workbooks](https://help.sigmacomputing.com/reference/list-workbooks)
        endpoint.

        - Retrieve the **elementId** for a custom SQL element by calling the
        [/v2/workbooks/{workbookId}/queries](https://help.sigmacomputing.com/reference/list-workbook-queries)
        endpoint.


        ### Usage scenarios

        - **Development and debugging:** Provides developers and analysts with
        the ability to retrieve and review the SQL code behind workbook
        elements, facilitating troubleshooting and enhancements.

        - **Educational insight:** Useful for training purposes or for users
        learning to understand the impact of various transformations and filters
        applied within their Sigma workbooks.


        ### Best practices

        - Ensure proper access controls are in place to manage who can view
        potentially sensitive query information.

        - Use this endpoint as part of a regular review process to ensure that
        all queries are optimized and up to date with current data schemas.
      tags:
        - Workbooks
      parameters:
        - name: workbookId
          in: path
          required: true
          schema:
            type: string
        - name: elementId
          in: path
          required: true
          schema:
            type: string
        - name: page
          in: query
          required: false
          schema:
            type: string
        - name: limit
          in: query
          required: false
          schema:
            type: number
            format: double
        - name: Authorization
          in: header
          description: OAuth authentication
          required: true
          schema:
            type: string
      responses:
        '200':
          description: The response body.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/workbooks_getElementQuery_Response_200'
servers:
  - url: https://api.sigmacomputing.com
    description: Server for GCP (US) hosted organizations
  - url: https://api.sa.gcp.sigmacomputing.com
    description: Server for GCP (KSA) hosted organizations
  - url: https://aws-api.sigmacomputing.com
    description: Server for AWS US (West) hosted organizations
  - url: https://api.us-a.aws.sigmacomputing.com
    description: Server for AWS US (East) hosted organizations
  - url: https://api.ca.aws.sigmacomputing.com
    description: Server for AWS Canada hosted organizations
  - url: https://api.eu.aws.sigmacomputing.com
    description: Server for AWS Europe hosted organizations
  - url: https://api.au.aws.sigmacomputing.com
    description: Server for AWS Australia and APAC hosted organizations
  - url: https://api.uk.aws.sigmacomputing.com
    description: Server for AWS UK hosted organizations
  - url: https://api.us.azure.sigmacomputing.com
    description: Server for Azure US hosted organizations
  - url: https://api.eu.azure.sigmacomputing.com
    description: Server for Azure Europe hosted organizations
  - url: https://api.ca.azure.sigmacomputing.com
    description: Server for Azure Canada hosted organizations
  - url: https://api.uk.azure.sigmacomputing.com
    description: Server for Azure United Kingdom hosted organizations
  - url: https://api.au.azure.sigmacomputing.com
    description: Server for Azure Australia hosted organizations
components:
  schemas:
    workbooks_getElementQuery_Response_200:
      type: object
      properties:
        elementId:
          type: string
        name:
          type: string
        sql:
          type: string
        error:
          type: string
      required:
        - elementId
      title: workbooks_getElementQuery_Response_200
  securitySchemes:
    OAuth:
      type: http
      scheme: bearer
      description: OAuth 2.0 authentication

```

## Examples



**Request**

```json
{}
```

**Response**

```json
{
  "elementId": "e7a9f3b2-4c1d-4f8a-9b2e-3d5f7a1c9b8e",
  "name": "Sales Revenue by Region",
  "sql": "SELECT region, SUM(sales_amount) AS total_sales FROM sales_data WHERE sales_date >= '2023-01-01' GROUP BY region ORDER BY total_sales DESC",
  "error": ""
}
```

**SDK Code**

```python
import requests

url = "https://api.sigmacomputing.com/v2/workbooks/workbookId/elements/elementId/query"

payload = {}
headers = {
    "Authorization": "<token>.",
    "Content-Type": "application/json"
}

response = requests.get(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.sigmacomputing.com/v2/workbooks/workbookId/elements/elementId/query';
const options = {
  method: 'GET',
  headers: {Authorization: '<token>.', 'Content-Type': 'application/json'},
  body: '{}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.sigmacomputing.com/v2/workbooks/workbookId/elements/elementId/query"

	payload := strings.NewReader("{}")

	req, _ := http.NewRequest("GET", url, payload)

	req.Header.Add("Authorization", "<token>.")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.sigmacomputing.com/v2/workbooks/workbookId/elements/elementId/query")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Get.new(url)
request["Authorization"] = '<token>.'
request["Content-Type"] = 'application/json'
request.body = "{}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.get("https://api.sigmacomputing.com/v2/workbooks/workbookId/elements/elementId/query")
  .header("Authorization", "<token>.")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('GET', 'https://api.sigmacomputing.com/v2/workbooks/workbookId/elements/elementId/query', [
  'body' => '{}',
  'headers' => [
    'Authorization' => '<token>.',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.sigmacomputing.com/v2/workbooks/workbookId/elements/elementId/query");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "<token>.");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "<token>.",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.sigmacomputing.com/v2/workbooks/workbookId/elements/elementId/query")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```