> ## 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 in CSV

> Given a query ID, returns the latest executed result of a query on Dune as CSV

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

You must pass parameter query\_id.

Returns the latest execution id and results (in CSV) 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/csv

  ```

  ```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
  result = dune.download_csv('2363421') 

  # 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/csv"

  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/csv', 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/csv"

  	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/csv",
    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/csv")
    .header("X-DUNE-API-KEY", "<x-dune-api-key>")
    .asString();

  ```
</RequestExample>


## OpenAPI

````yaml GET /v1/query/{query_id}/results/csv
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/csv:
    get:
      summary: >-
        Given a query ID, returns the latest executed result of a query on Dune
        as CSV
      description: >-
        Given a query ID, returns the latest executed result of a query on Dune
        as CSV
      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:
            text/plain:
              schema:
                type: string
          description: OK
        '400':
          content:
            text/plain:
              schema:
                $ref: '#/components/schemas/models.Error400'
          description: Bad Request
        '404':
          content:
            text/plain:
              schema:
                $ref: '#/components/schemas/models.Error404'
          description: Not Found
        '500':
          content:
            text/plain:
              schema:
                $ref: '#/components/schemas/models.Error500'
          description: Internal Server Error
components:
  schemas:
    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

````