> ## 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.

# Result Filtering

> Filter query results server-side using SQL-like WHERE clauses - unique to Dune's API

<Note>
  **Unique to Dune:** Server-side result filtering is a powerful feature that sets Dune's API apart. Filter millions of rows using SQL-like WHERE clauses without transferring unnecessary data or processing client-side.
</Note>

## Overview

Dune's API supports sophisticated filtering on all `/results` endpoints, allowing you to refine query results server-side. Apply filters on rows and columns to dramatically reduce bandwidth and processing time.

**Benefits:**

* **Reduce bandwidth:** Only transfer the data you need
* **Save processing time:** Filter server-side before data transfer
* **Simplify client code:** No need for complex client-side filtering logic
* **Lower costs:** Minimize data transfer and API calls

**Available on these endpoints:**

* [Get Execution Results](./endpoint/get-execution-result)
* [Get Execution Results CSV](./endpoint/get-execution-result-csv)
* [Get Query Results](./endpoint/get-query-result)
* [Get Query Results CSV](./endpoint/get-query-result-csv)

Filtering can be effectively used in conjunction with [pagination](./pagination) and [sorting](./sorting) to further enhance query efficiency and relevance. See an example of filtering in action with [this Dune farcaster frame](/learning/how-tos/dune-frames).

#### Example Filtering Request

<Tabs>
  <Tab title="Python SDK">
    ```python theme={null}
    from dune_client.client import DuneClient

    # setup Dune Python client
    dune = DuneClient()

    query_result = dune.get_latest_result_dataframe(
        query=3567562 # https://dune.com/queries/3567562
        , filters="overtip_amount > 0"
        , columns=["donor_fname","overtip_amount","days_overtipped","overall_tip_given_amount","overall_avg_tip_amount"]
        , sort_by=["overall_tip_given_amount desc"]
    )

    print(query_result)

    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    curl -X GET 'https://api.dune.com/api/v1/query/{{query_id}}/results?limit=10&filters=block_time%3E%272024-03-01%27&columns=tx_from%2Ctx_to%2Ctx_hash%2Camount_usd&sort_by=amount_usd%20desc%2Cblock_time' \
    -H 'x-dune-api-key:{{api_key}}’
    ```
  </Tab>

  <Tab title="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>"}

    params = {
        "limit": 10,
        "filters": "block_time > '2024-03-01'",
        "columns": "tx_from,tx_to,tx_hash,amount_usd",
        "sort_by": "amount_usd desc, block_time"
        }

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

    print(response.text)

    ```
  </Tab>

  <Tab title="Javascript">
    ```javascript theme={null}

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

    const queryParams = new URLSearchParams({
        limit: 10,
        filters: "block_time > '2024-03-01'",
        columns: "tx_from,tx_to,tx_hash,amount_usd",
        sort_by: "amount_usd desc, block_time"
    });
    const url = `https://api.dune.com/api/v1/query/{query_id}/results?${queryParams}`;

    fetch(url, options)
        .then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.error(err));


    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}

    package main

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

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

        // Create query parameters
        params := url.Values{}
        params.Set("limit", "10")
        params.Set("filters", "block_time > '2024-03-01'")
        params.Set("columns", "tx_from,tx_to,tx_hash,amount_usd")
        params.Set("sort_by", "amount_usd desc, block_time")

        // Add parameters to URL
        fullURL := fmt.Sprintf("%s?%s", url, params.Encode())

        req, _ := http.NewRequest("GET", fullURL, 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))
    }
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php

    $curl = curl_init();

    $url = "https://api.dune.com/api/v1/query/{query_id}/results";
    $queryParams = http_build_query([
        'limit' => 10,
        'filters' => "block_time > '2024-03-01'",
        'columns' => "tx_from,tx_to,tx_hash,amount_usd",
        'sort_by' => "amount_usd desc, block_time",
    ]);
    $url .= '?' . $queryParams;

    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        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;
    }
    ?>
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}

    import kong.unirest.HttpResponse;
    import kong.unirest.Unirest;

    public class Main {
        public static void main(String[] args) {
            HttpResponse<String> response = Unirest.get("https://api.dune.com/api/v1/query/{query_id}/results")
                    .header("X-DUNE-API-KEY", "<x-dune-api-key>")
                    .queryString("limit", 10)
                    .queryString("filters", "block_time > '2024-03-01'")
                    .queryString("columns", "tx_from,tx_to,tx_hash,amount_usd")
                    .queryString("sort_by", "amount_usd desc, block_time")
                    .asString();

            System.out.println(response.getBody());
        }
    }
    ```
  </Tab>
</Tabs>

### Filtering Parameters

#### `filters`

* **Type:** `string`
* **Description:** Allows specifying criteria to filter rows in the result set. It functions similarly to a SQL `WHERE` clause. If omitted, all results are returned.

<Note>
  - Use the format `<column_name> <operator> <value>` for criteria, for example, `block_time >= '2024-03-05 15:03'`.
  - Combine criteria using parentheses and logical operators `AND` / `OR`, e.g., `block_time >= '2024-03-05 15:03' AND (project = 'uniswap' OR project = 'balancer')`.
  - The `IN` operator is permitted, as in `tx_to IN (0x6a3e4b7e23661108aaec70266c468e6c679ae022, 0xdbf89389504e39f03fbb6bdd601aabb6bfbbed71)`.
  - The `NOT` operator is not supported; using `NOT IN` or `NOT LIKE` will produce an error.
  - For column names with special characters (e.g., spaces, emojis, dashes, dots), enclose them in double quotes: `"special, column" = 'ABC'`.
  - Values must be strings or numbers. SQL expressions like `now() - interval '1' day` are not allowed.
  - Dates and times should be formatted as strings, e.g., `block_time > '2023-01-03'`.
</Note>

#### `columns`

* **Type:** `string`
* **Description:** Specifies the column names to include in the result set. If omitted, all columns are returned.

<Note>
  - List column names without spaces, e.g., use `project,block_time,amount_usd` instead of `project, block_time, amount_usd`.
  - Specifying columns helps limit the results to essential data, reducing the data cost of the call.
</Note>

## Common Filtering Patterns

### Filter by Time Range

```bash theme={null}
# Last 24 hours
filters="block_time > '2024-03-05'"

# Specific time range
filters="block_time >= '2024-03-01' AND block_time < '2024-04-01'"

# Recent data (note: relative time expressions are NOT supported in filters)
# Instead, calculate the date client-side
filters="block_time > '2024-03-10 15:30'"
```

### Filter by Value Thresholds

```bash theme={null}
# Transactions above $1000
filters="amount_usd > 1000"

# Volume between ranges
filters="volume_usd >= 10000 AND volume_usd <= 100000"

# Non-null values
filters="amount_usd IS NOT NULL"
```

### Filter by Category

```bash theme={null}
# Single protocol
filters="project = 'uniswap'"

# Multiple protocols (using OR)
filters="project = 'uniswap' OR project = 'sushiswap'"

# Using IN operator
filters="project IN ('uniswap', 'sushiswap', 'curve')"

# Specific blockchain
filters="blockchain = 'ethereum'"
```

### Complex Conditions

```bash theme={null}
# Combine multiple conditions
filters="blockchain = 'ethereum' AND amount_usd > 1000 AND block_time > '2024-03-01'"

# Use parentheses for grouping
filters="(project = 'uniswap' OR project = 'sushiswap') AND amount_usd > 10000"

# Filter with pattern matching
filters="token_symbol LIKE 'WETH%'"

# Address filtering
filters="tx_to IN ('0x6a3e4b7e23661108aaec70266c468e6c679ae022', '0xdbf89389504e39f03fbb6bdd601aabb6bfbbed71')"
```

### Filter with Column Selection

```python theme={null}
# Python SDK example: Get only specific columns for large trades
results = dune.get_latest_result_dataframe(
    query=3493826,
    filters="amount_usd > 10000 AND blockchain = 'ethereum'",
    columns="tx_hash,tx_from,tx_to,amount_usd,block_time"
)
```

<Tip>
  **Performance tip:** Combine filtering with column selection to minimize data transfer. For example, instead of fetching all 50 columns for millions of rows, fetch only the 5 columns you need for 1000 filtered rows.
</Tip>

## Real-World Examples

### Example 1: Whale Transactions

```python theme={null}
from dune_client import DuneClient

dune = DuneClient(api_key="YOUR_API_KEY")

# Get large USDC transfers in the last day
results = dune.get_latest_result_dataframe(
    query=3493826,
    filters="token_symbol = 'USDC' AND amount_usd > 1000000 AND block_time > '2024-03-10'",
    columns="tx_hash,tx_from,tx_to,amount_usd,block_time",
    sort_by="amount_usd desc"
)

print(f"Found {len(results)} whale transactions")
```

### Example 2: Protocol-Specific Analytics

```typescript theme={null}
import { DuneClient } from '@duneanalytics/client';

const dune = new DuneClient('YOUR_API_KEY');

// Get Uniswap V3 trades on Arbitrum
const results = await dune.getLatestResults({
  queryId: 3493826,
  filters: "project = 'uniswap' AND version = '3' AND blockchain = 'arbitrum'",
  columns: "trader,token_bought_symbol,token_sold_symbol,amount_usd",
  limit: 100
});
```

### Example 3: Token-Specific Monitoring

```bash theme={null}
# Monitor recent trades for a specific token pair
curl -X GET \
  'https://api.dune.com/api/v1/query/3493826/results?filters=token_bought_symbol%20%3D%20%27WETH%27%20AND%20token_sold_symbol%20%3D%20%27USDC%27%20AND%20block_time%20%3E%20%272024-03-10%27&columns=amount_usd%2Cprice%2Cblock_time&sort_by=block_time%20desc' \
  -H 'X-DUNE-API-KEY: YOUR_API_KEY'
```

### Example 4: Multi-Chain Analysis

```python theme={null}
# Compare volumes across chains for the same protocol
blockchains = ['ethereum', 'polygon', 'arbitrum', 'optimism']

for chain in blockchains:
    results = dune.get_latest_result_dataframe(
        query=3493826,
        filters=f"blockchain = '{chain}' AND project = 'uniswap'",
        columns="blockchain,amount_usd"
    )
    total_volume = results['amount_usd'].sum()
    print(f"{chain}: ${total_volume:,.2f}")
```

## Filtering Best Practices

<AccordionGroup>
  <Accordion title="Always filter time ranges">
    Reduce the amount of data scanned by filtering by `block_time`:

    ```bash theme={null}
    # ✅ Good - filters recent data
    filters="block_time > '2024-03-01' AND amount_usd > 1000"

    # ❌ Less efficient - scans all historical data
    filters="amount_usd > 1000"
    ```
  </Accordion>

  <Accordion title="Combine filters with column selection">
    Minimize bandwidth by only requesting needed columns:

    ```bash theme={null}
    # ✅ Optimal - filtered rows, selected columns
    filters="amount_usd > 10000"&columns="tx_hash,amount_usd,block_time"

    # ❌ Wasteful - fetches all columns
    filters="amount_usd > 10000"
    ```
  </Accordion>

  <Accordion title="Use IN for multiple values">
    More efficient than multiple OR conditions:

    ```bash theme={null}
    # ✅ Better
    filters="blockchain IN ('ethereum', 'polygon', 'arbitrum')"

    # ✅ Also valid but longer
    filters="blockchain = 'ethereum' OR blockchain = 'polygon' OR blockchain = 'arbitrum'"
    ```
  </Accordion>

  <Accordion title="Be specific with data types">
    Use proper quoting for strings, no quotes for numbers:

    ```bash theme={null}
    # ✅ Correct
    filters="blockchain = 'ethereum' AND amount_usd > 1000"

    # ❌ Wrong - amount_usd should not be quoted
    filters="blockchain = 'ethereum' AND amount_usd > '1000'"
    ```
  </Accordion>

  <Accordion title="Handle special column names">
    Use double quotes for columns with special characters:

    ```bash theme={null}
    # ✅ Correct for special characters
    filters="\"token.symbol\" = 'USDC'"

    # ✅ No quotes needed for normal names
    filters="token_symbol = 'USDC'"
    ```
  </Accordion>
</AccordionGroup>

## Limitations

<Warning>
  * **No SQL expressions:** Filters must use literal values. Expressions like `now() - interval '1' day` are not supported. Calculate values client-side instead.
  * **No NOT operator:** `NOT IN` and `NOT LIKE` are not supported. Use positive conditions instead.
  * **No subqueries:** Filters cannot contain subqueries. Use parameterized queries for complex logic.
  * **String and number values only:** Filters only support string and numeric literals.
</Warning>

## Filtered Response

<Accordion title="Example filtered response">
  ```json theme={null}
      {
          "execution_id": "01HR8AGD6CWGHGP1BN3Z1SJ4MD",
          "query_id": 3493826,
          "is_execution_finished": true,
          "state": "QUERY_STATE_COMPLETED",
          "submitted_at": "2024-03-05T22:07:22.828653Z",
          "expires_at": "2024-06-03T22:07:53.36647Z",
          "execution_started_at": "2024-03-05T22:07:24.013663281Z",
          "execution_ended_at": "2024-03-05T22:07:53.366469062Z",
          "result": {
              "rows": [
                  {
                      "amount_usd": null,
                      "block_time": "2024-03-05 20:50:59.000 UTC",
                      "tx_from": "0x38032f326436fdb9c7a9b359e90010f86b8ab482",
                      "tx_hash": "0xce6f59cf2f0b395d8fc33e49d1f5db5686be95555135fd8126bc7c59327cd9be",
                      "tx_to": "0x061b87122ed14b9526a813209c8a59a633257bab"
                  },
                  {
                      "amount_usd": null,
                      "block_time": "2024-03-05 20:49:33.000 UTC",
                      "tx_from": "0xb46b909be665d75f833be22c6e6285ba5ad74dfa",
                      "tx_hash": "0x1f1725ebe374b1ffb50047055b793b2be6a8cb07ab75fd685b95e842953da4ca",
                      "tx_to": "0x1111111254eeb25477b68fb85ed929f73a960582"
                  },
                  {
                      "amount_usd": null,
                      "block_time": "2024-03-05 20:48:53.000 UTC",
                      "tx_from": "0x40014275b332f38423fa0de39939d26c7294ffc0",
                      "tx_hash": "0xb4364656c20007fb1d7bfa93d87fc6fe345a91b10661835d1a54d1ac7761a244",
                      "tx_to": "0x1111111254eeb25477b68fb85ed929f73a960582"
                  },
                  {
                      "amount_usd": 1397.903560808159,
                      "block_time": "2024-03-05 20:48:03.000 UTC",
                      "tx_from": "0xb46b909be665d75f833be22c6e6285ba5ad74dfa",
                      "tx_hash": "0x818f701a6c7dcf78a090cfd8324da5896005c2a6d8e3ec5ac2c29cfa5e67f5d9",
                      "tx_to": "0x1111111254eeb25477b68fb85ed929f73a960582"
                  },
                  {
                      "amount_usd": null,
                      "block_time": "2024-03-05 20:47:55.000 UTC",
                      "tx_from": "0x50758bdc1735e94401ed73eb7e8bde482766819c",
                      "tx_hash": "0x1dc342dc397ffa7b433fa64280fe9f4a7e0b51409e9abc9fde61bc9b85c938be",
                      "tx_to": "0x4c4af8dbc524681930a27b2f1af5bcc8062e6fb7"
                  },
                  {
                      "amount_usd": null,
                      "block_time": "2024-03-05 20:47:55.000 UTC",
                      "tx_from": "0x50758bdc1735e94401ed73eb7e8bde482766819c",
                      "tx_hash": "0x1dc342dc397ffa7b433fa64280fe9f4a7e0b51409e9abc9fde61bc9b85c938be",
                      "tx_to": "0x4c4af8dbc524681930a27b2f1af5bcc8062e6fb7"
                  },
                  {
                      "amount_usd": null,
                      "block_time": "2024-03-05 20:47:53.000 UTC",
                      "tx_from": "0xfa3dc8db10e7c2f7dfa87e86bba6257066731bc1",
                      "tx_hash": "0x0d34634a9438ce241e2870b23e70a008c8db839ba38daadc1074c9b1a52be7c7",
                      "tx_to": "0xba12222222228d8ba445958a75a0704d566bf2c8"
                  },
                  {
                      "amount_usd": 2.753641952846242,
                      "block_time": "2024-03-05 20:47:53.000 UTC",
                      "tx_from": "0xfa3dc8db10e7c2f7dfa87e86bba6257066731bc1",
                      "tx_hash": "0x0d34634a9438ce241e2870b23e70a008c8db839ba38daadc1074c9b1a52be7c7",
                      "tx_to": "0xba12222222228d8ba445958a75a0704d566bf2c8"
                  },
                  {
                      "amount_usd": null,
                      "block_time": "2024-03-05 20:47:53.000 UTC",
                      "tx_from": "0xfa3dc8db10e7c2f7dfa87e86bba6257066731bc1",
                      "tx_hash": "0x0d34634a9438ce241e2870b23e70a008c8db839ba38daadc1074c9b1a52be7c7",
                      "tx_to": "0xba12222222228d8ba445958a75a0704d566bf2c8"
                  },
                  {
                      "amount_usd": 1798.8186143812122,
                      "block_time": "2024-03-05 20:47:49.000 UTC",
                      "tx_from": "0xb46b909be665d75f833be22c6e6285ba5ad74dfa",
                      "tx_hash": "0xcf8d9873f017a8ba9e624c3bb61bede8e11c194965690026cd394f20c55f896a",
                      "tx_to": "0x1111111254eeb25477b68fb85ed929f73a960582"
                  }
              ],
              "metadata": {
                  "column_names": [
                      "block_time",
                      "tx_from",
                      "tx_to",
                      "tx_hash",
                      "amount_usd"
                  ],
                  "row_count": 10,
                  "result_set_bytes": 2042,
                  "total_row_count": 100,
                  "total_result_set_bytes": 56496,
                  "datapoint_count": 50,
                  "pending_time_millis": 1185,
                  "execution_time_millis": 29352
              }
          },
          "next_uri": "https://api.dune.com/api/v1/execution/01HR8AGD6CWGHGP1BN3Z1SJ4MD/results?columns=block_time%2Ctx_from%2Ctx_to%2Ctx_hash%2Camount_usd&filters=block_time+%3E+%272024-03-01%27&limit=10&offset=10",
          "next_offset": 10
      }
  ```
</Accordion>
