> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dune.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Latest Query Result

> Given a query ID, returns the latest executed result of a query on Dune in JSON format

<Info>
  Minimum required API key scope: `Read`
</Info>

You must pass parameter query\_id.

Returns the latest execution id and results (in JSON) of that latest run, regardless of the job id/run or if it is run in the app or the api.

The query specified must either be public or a query you have ownership of (you or a team you belong to have ownership).

<Tip>
  * This endpoint does NOT trigger an execution but does **consume credits based on the result size**. See [Billing](/api-reference/overview/billing) for details.
  * Read more on [Filtering](../filtering), [Sorting](../sorting), and [Sampling](../sampling) to learn more about flexibly grabbing query results.
  * Read more on [Pagination](../pagination) to get the most out of the API and handle large results.
</Tip>

<Info>
  * Dune internally has a maximum query result size limit (which currently is 32GB). If your query yields more than 32GB of data, the result will be truncated in storage. In such cases, pulling the result data (using pagination) but without specifying `allow_partial_results` set to true will trigger an error message: "error": "Partial Result, please request with 'allows\_partial\_results=true'". If you wish to retrieve partial results, you can pass the parameter `allow_partial_results=true`. But please make sure you indeed want to fetch the truncated result.
</Info>

<Accordion title="Execute query and get result in one call">
  <Tip> If you are using the [Python SDK](https://github.com/duneanalytics/dune-client/tree/d2195b2a9577e2dcae5d2600cb3eddce20987f38), you can directly execute and fetch result in one function call, like below: </Tip>

  ```python Python SDK  theme={null}

  import json
  from dune_client.types import QueryParameter
  from dune_client.client import DuneClient
  from dune_client.query import QueryBase

  # setup Dune Python client
  dune = DuneClient()

  ```

  Use `run_query` to get result in JSON,
  `run_query_csv` to get result in CSV format,
  and `run_query_dataframe` to get result in Pandas dataframe

  ```

  result = dune.run_query(
      query=query # pass in query to run 
      , performance = 'large' # optionally define which tier to run the execution on (default is "medium")
      )

  ```
</Accordion>

<RequestExample>
  ```bash cURL theme={null}

  curl --request GET \
    --url https://api.dune.com/api/v1/query/{query_id}/results
    
  ```

  ```python Python SDK theme={null}

  '''
  Download Dune Python SDK by running `pip install dune-client`
  For more info, visit the GitHub repository: https://github.com/duneanalytics/dune-client/tree/d2195b2a9577e2dcae5d2600cb3eddce20987f38
  '''

  import json
  from dune_client.types import QueryParameter
  from dune_client.client import DuneClient
  from dune_client.query import QueryBase

  # setup Dune Python client
  dune = DuneClient()

  # pass in the query_id
  # optionally specify a `max_age_hours` to re-run the query if the data is too outdated
  result =  dune.get_latest_result('2363421', max_age_hours=8) 

  # can also call `get_latest_result_dataframe` method to get latest result in Python Pandas dataframe format

  ```

  ```python Python theme={null}
  import requests

  url = "https://api.dune.com/api/v1/query/{query_id}/results"

  headers = {"X-DUNE-API-KEY": "<x-dune-api-key>"}

  response = requests.request("GET", url, headers=headers)

  print(response.text)

  ```

  ```javascript Javascript theme={null}
  const options = {method: 'GET', headers: {'X-DUNE-API-KEY': '<x-dune-api-key>'}};

  fetch('https://api.dune.com/api/v1/query/{query_id}/results', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));

  ```

  ```go Go theme={null}
  package main

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

  func main() {

  	url := "https://api.dune.com/api/v1/query/{query_id}/results"

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

  	req.Header.Add("X-DUNE-API-KEY", "<x-dune-api-key>")

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

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

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

  }

  ```

  ```php PHP theme={null}
  <?php

  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => "https://api.dune.com/api/v1/query/{query_id}/results",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => [
      "X-DUNE-API-KEY: <x-dune-api-key>"
    ],
  ]);

  $response = curl_exec($curl);
  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    echo "cURL Error #:" . $err;
  } else {
    echo $response;
  }

  ```

  ```java Java theme={null}
  HttpResponse<String> response = Unirest.get("https://api.dune.com/api/v1/query/{query_id}/results")
    .header("X-DUNE-API-KEY", "<x-dune-api-key>")
    .asString();

  ```
</RequestExample>


## OpenAPI

````yaml GET /v1/query/{query_id}/results
openapi: 3.0.1
info:
  contact: {}
  description: Dune API
  title: DuneAPI
  version: '1.0'
servers:
  - url: https://api.dune.com/api
security: []
paths:
  /v1/query/{query_id}/results:
    get:
      summary: Get Latest Query Result
      description: >-
        Given a query ID, returns the latest executed result of a query on Dune
        in JSON format
      parameters:
        - description: API Key for the service
          in: header
          name: X-Dune-Api-Key
          required: true
          schema:
            type: string
        - description: Alternative to using the X-Dune-Api-Key header
          in: query
          name: api_key
          schema:
            type: string
        - description: Query ID
          in: path
          name: query_id
          required: true
          schema:
            type: string
        - description: >-
            This enables returning a query result that was too large and only a
            partial result is

            available. By default, allow_partial_results is set to false and a
            failed state is returned.
          in: query
          name: allow_partial_results
          schema:
            type: boolean
        - description: >-
            Specifies a comma-separated list of column names to return. If
            omitted, all columns are included.

            Tip: use this to limit the result to specific columns, reducing
            datapoints cost of the call.
          in: query
          name: columns
          schema:
            type: string
        - description: >-
            Expression to filter out rows from the results to return. This
            expression is similar to

            a SQL WHERE clause. More details about it in the Filtering section
            of the doc.

            This parameter is incompatible with sample_count.
          in: query
          name: filters
          schema:
            type: string
        - description: >-
            To bypass the default max credits per request limit, set
            ignore_max_credits_per_request=true
          in: query
          name: ignore_max_credits_per_request
          schema:
            type: boolean
        - description: >-
            Limit number of rows to return. This together with 'offset' allows
            easy pagination through

            results in an incremental and efficient way. This parameter is
            incompatible

            with sampling (sample_count).
          in: query
          name: limit
          schema:
            type: integer
        - description: >-
            Offset row number to start (inclusive, first row means offset=0)
            returning results

            from. This together with 'limit' allows easy pagination through
            results in an

            incremental and efficient way. This parameter is incompatible with
            sampling (sample_count).
          in: query
          name: offset
          schema:
            type: integer
        - in: query
          name: queryID
          required: true
          schema:
            type: integer
        - description: >-
            Number of rows to return from the result by sampling the data. This
            is useful when you

            want to get a uniform sample instead of the entire result. If the
            result has less

            than the sample count, the entire result is returned. Note that this
            will return a

            randomized sample, so not every call will return the same result.
            This parameter is

            incompatible with `offset`, `limit`, and `filters` parameters.
          in: query
          name: sample_count
          schema:
            type: integer
        - description: >-
            Expression to define the order in which the results should be
            returned. This expression

            is similar to a SQL ORDER BY clause. More details about it in the
            Sorting section of the doc.
          in: query
          name: sort_by
          schema:
            type: string
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/models.ReadExecutionResultResponse'
          description: OK
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/models.Error400'
          description: Bad Request
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/models.Error404'
          description: Not Found
        '500':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/models.Error500'
          description: Internal Server Error
components:
  schemas:
    models.ReadExecutionResultResponse:
      properties:
        cancelled_at:
          description: Timestamp of when the query execution was cancelled, if applicable.
          example: '2024-12-20T11:04:18.724658237Z'
          type: string
        error:
          allOf:
            - $ref: '#/components/schemas/models.QueryResultError'
          description: >-
            In case the execution had an error, this object will contain the
            error details
        execution_ended_at:
          description: Timestamp of when the query execution ended.
          example: '2024-12-20T11:04:18.724658237Z'
          type: string
        execution_id:
          description: Unique identifier for the execution of the query.
          example: 01HKZJ2683PHF9Q9PHHQ8FW4Q1
          type: string
        execution_started_at:
          description: Timestamp of when the query execution started.
          example: '2024-12-20T11:04:18.724658237Z'
          type: string
        expires_at:
          description: Timestamp of when the query result expires.
          example: '2024-12-20T11:04:18.724658237Z'
          type: string
        is_execution_finished:
          description: >-
            Whether the state of the query execution is terminal. This can be
            used for polling purposes.
          example: true
          type: boolean
        next_offset:
          description: Offset that can be used to retrieve the next page of results.
          example: 100
          type: integer
        next_uri:
          description: URI that can be used to fetch the next page of results.
          example: >-
            https://api.dune.com/api/v1/execution/01HKZJ2683PHF9Q9PHHQ8FW4Q1/results?offset=100&limit=100
          type: string
        query_id:
          description: Unique identifier of the query.
          example: 1234
          type: integer
        result:
          allOf:
            - $ref: '#/components/schemas/models.QueryResultData'
          description: >-
            The object containing the results and metadata of the query
            execution
        state:
          description: The state of the query execution.
          example: QUERY_STATE_COMPLETED
          type: string
        submitted_at:
          description: Timestamp of when the query was submitted.
          example: '2024-12-20T11:04:18.724658237Z'
          type: string
      type: object
    models.Error400:
      properties:
        error:
          example: Bad Request
          type: string
      type: object
    models.Error404:
      properties:
        error:
          example: Object not found
          type: string
      type: object
    models.Error500:
      properties:
        error:
          example: Internal error
          type: string
      type: object
    models.QueryResultError:
      properties:
        message:
          description: A descriptive message about the error.
          example: 'Error: Line 1:1: mismatched input ''selecdt'''
          type: string
        metadata:
          allOf:
            - $ref: '#/components/schemas/models.SyntaxErrorMetadata'
          description: Metadata about the syntax error that occurred, if applicable.
        type:
          description: The type of error that occurred.
          example: syntax_error
          type: string
      type: object
    models.QueryResultData:
      properties:
        metadata:
          allOf:
            - $ref: '#/components/schemas/models.ExecutionResultMetadata'
          description: >-
            Metadata about the execution of the query, including details like
            column names,

            row counts, and execution times.
        rows:
          description: >-
            A list of rows. A row is dictionary of key-value pairs returned by
            the query,

            each pair corresponding to a column
          items:
            $ref: '#/components/schemas/models.Row'
          type: array
        update_type:
          description: The type of update operation from Trino (e.g., "SET SESSION")
          type: string
      type: object
    models.SyntaxErrorMetadata:
      properties:
        column:
          description: The column number at which the syntax error occurred.
          example: 73
          type: integer
        line:
          description: The line number at which the syntax error occurred in the query.
          example: 10
          type: integer
      type: object
    models.ExecutionResultMetadata:
      properties:
        column_names:
          description: Names of the columns in the result set.
          example:
            - Rank
            - Project
            - Volume
          items:
            type: string
          type: array
        column_types:
          description: Types of the columns in the result set.
          example:
            - double
            - varchar
            - bigint
          items:
            type: string
          type: array
        datapoint_count:
          description: >-
            Results cell count is used for billing/pricing plans

            here we expose the these values to the user, so that they can track
            their costs
          example: 1000
          type: integer
        execution_time_millis:
          description: Time in milliseconds that the query took to execute.
          example: 1000
          type: integer
        pending_time_millis:
          description: Time in milliseconds that the query was pending before execution.
          example: 1000
          type: integer
        result_set_bytes:
          description: >-
            ResultSetBytes represents the raw data bytes returned by the SQL
            execution engine, it includes:
             + total nr of bytes used on 1 line with all the column names (the header of the result set)
             + total nr of bytes for all the row values (the result set of rows)

            it doesn't include overheads such as the presence of column names
            for every row in the JSON result type.

            it also doesn't include opmitizations such as compression
          example: 1000
          type: integer
        row_count:
          description: Number of rows in the result set for the current page of results.
          example: 10
          type: integer
        total_result_set_bytes:
          description: >-
            Total number of bytes in the result set. This doesn't include the
            json representation overhead.
          example: 10000
          type: integer
        total_row_count:
          description: Number of rows in the result set for the entire result set.
          example: 1000
          type: integer
      type: object
    models.Row:
      additionalProperties: {}
      type: object

````