# Dataset SQL Query - DuckDB Joins, GROUP BY & Window Functions (`actor-forge/dataset-sql-transform`) Actor

Run one SQL query (DuckDB) over your Apify datasets, CSV/JSON/Parquet URLs or pasted rows: filter, join, GROUP BY, pivot, window functions, nested JSON. Result rows go to a new dataset (+ CSV/Parquet). $0.20 per 1,000 result rows + $0.001 per 1,000 rows read.

- **URL**: https://apify.com/actor-forge/dataset-sql-transform.md
- **Developed by:** [ActorForge](https://apify.com/actor-forge) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.20 / 1,000 result rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Dataset SQL Query - DuckDB Joins, GROUP BY & Window Functions

Run one SQL query (DuckDB) over your Apify datasets, CSV/JSON/Parquet URLs or pasted rows: filter, join, GROUP BY, pivot, window functions, nested JSON. Result rows go to a new dataset (+ CSV/Parquet). $0.20 per 1,000 result rows + $0.001 per 1,000 rows read.

**Ask any question of your scraped data in SQL, without leaving Apify.** Pick one or more **Apify datasets**, add **CSV, TSV, JSON, JSON Lines or Parquet file URLs** or paste rows, and run **one SQL query** on a real analytical engine (**DuckDB**): `WHERE` filters, `JOIN`s across datasets (e.g. jobs × companies, products × competitor prices), `GROUP BY` with counts, sums and averages, **window functions** (rank, running totals, `QUALIFY row_number() = 1` to keep the latest row per key), `PIVOT`, `regexp_extract`, date maths and **nested JSON access** (`address.city`, `tags[1]`, `json_extract`). Each source becomes a named table; every column and its detected type is listed in the log. The result rows land in a **new dataset** you can export, chain to another Actor or send to Make/n8n/Zapier, and can also be saved as **CSV, Parquet or JSON Lines** files. Use it after a scheduled scrape to build daily reports, clean and reshape rows for a CRM, or deduplicate with exactly the rule you want. It is **read-only by design**: one SELECT-type statement, no file or network access from SQL, and with **limited permissions** it can read only the datasets you pick. **$0.20 per 1,000 result rows + $0.001 per 1,000 input rows read**, so a GROUP BY over 100,000 rows that returns 20 rows costs about $0.10.

### What data does it return?

Every run outputs clean, schema-validated rows like these:

| category | products | avg_price | best_rating |
| --- | --- | --- | --- |
| jackets | 3 | 149.17 | 4.8 |
| shoes | 2 | 109.45 | 4.6 |
| socks | 1 | 12.5 | 4.4 |

### How much does it cost?

Transparent pay-per-event pricing — you only pay for what you get, and the
actor **always respects your run budget**: set a maximum total charge and it
stops cleanly at the cap instead of overrunning.

| Event | Price | Charged | Worked example |
| --- | --- | --- | --- |
| `result-row` | $0.0002 | per result row delivered to the dataset ($0.20 per 1,000) | Filter 50,000 scraped products down to 4,000 rows = $0.80 + $0.05 input = $0.85 |
| `input-rows-1k` | $0.001 | per started block of 1,000 input rows loaded from datasets, files or pasted rows | GROUP BY over 100,000 rows returning 20 rows = $0.10 + $0.004 = $0.104 |
| `apify-actor-start` | $0.00005 | per run per GB of memory (platform start fee) | One run at 1 GB = $0.00005 |

### Input options

| Field | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sql` | string | yes | — | One read-only DuckDB query: SELECT / WITH / FROM-first / PIVOT / SUMMARIZE / DESCRIBE, with joins, GROUP BY, window functions, QUALIFY, regexp\_\*, nested fields (address.city, tags\[1]) and json_extract. Tables: rows (pasted rows), dataset_1, dataset_2 … (or your names), file_1 … (or name=url); the first table is also called data. Quote column names with spaces: "Region Name". Writes, ATTACH, INSTALL/LOAD, settings and file/URL functions are refused. |
| `rows` | array | no | — | Optional rows pasted as a JSON array of objects (up to 100,000). Queried as the table rows. |
| `datasetIds` | array | no | — | Apify datasets to query (pick them, or pass dataset IDs via the API). In an integration that runs this Actor after another one, set this field to \["{{resource.defaultDatasetId}}"] to query the triggering run's results. Picking a dataset gives this run read access to it; nothing else on your account is readable. Each becomes a table: dataset_1, dataset_2 … or the names below. |
| `datasetTableNames` | array | no | — | Optional names for the datasets above, in the same order (e.g. jobs, companies). Letters, digits and \_. |
| `fileUrls` | array | no | — | Public file URLs, up to 200 MB each. Write name=https://… to choose the table name (e.g. countries=https://…/countries.csv). CSV delimiter and column types are detected; JSON may be an array, an object with an items/data/results array, or JSON Lines. |
| `outputFiles` | array | no | `[]` | Optional. Writes the delivered rows as RESULT-csv / RESULT-parquet / RESULT-jsonl records in the run's key-value store (links in the OUTPUT record). Free. |
| `maxResults` | integer | no | `1000000` | Deliver at most this many result rows (the rest are not charged). A LIMIT in your SQL works too. |
| `maxInputRows` | integer | no | `2000000` | Stop loading sources after this many rows in total (a warning is logged; aggregates then cover only the loaded rows). Raise the run memory for many millions of rows. |
| `queryTimeoutSecs` | integer | no | `300` | Stop the query if it runs longer than this. |

### Limits & honest notes

- Dialect: DuckDB SQL (PostgreSQL-like): CTEs, all join types, GROUP BY ALL, window functions, QUALIFY, PIVOT/UNPIVOT, list and struct functions, regexp\_\*, strftime/date_trunc, json_extract and ->> operators. Each source is a table (rows, dataset_1 …, file_1 … or your names; the first is also called data); the log lists every column with its type.
- One query per run. It must be a single read-only statement (SELECT, WITH, FROM-first, VALUES, TABLE, PIVOT/UNPIVOT, SUMMARIZE, DESCRIBE). Table names are fixed by the input; the query cannot open other files, URLs or databases.
- Datasets: with limited permissions the run can read only the datasets picked in the Datasets field (or passed by ID via the API or an integration). If a source cannot be read, the query is not run (a partial join would be wrong) and nothing is charged.
- Integrations: when run after another Actor, set Datasets to \["{{resource.defaultDatasetId}}"] to query the triggering run's results (limited permissions grant read access only to datasets given in the Datasets field).
- Input rows are capped by Max input rows (default 2 million, up to 10 million) and by your spend limit; if a table is cut short, the log and OUTPUT say so and aggregates cover only the loaded rows.
- Column types are detected from the data: all dataset rows for JSON sources, the first 100,000 rows for CSV. CSV IDs with leading zeros may be read as numbers unless the column also has non-numeric values; cast in SQL if needed.
- Files are downloaded once, up to 200 MB each. Private and internal network addresses are refused at every redirect hop.
- The query runs with the run's memory (DuckDB gets about 55% and spills to disk) and stops after the query timeout (default 300 s).
- Result values: BIGINT/HUGEINT beyond 2^53 are returned as text, DATE as YYYY-MM-DD, TIMESTAMP as ISO 8601, BLOB as text.
- When the query returns no rows, the run adds one free row with \_status and \_message and still succeeds. Invalid input or SQL errors add a free status row and fail the run with the DuckDB error message.

### Related ActorForge actors

- [Merge & Deduplicate Datasets](https://apify.com/actor-forge/dataset-merge-dedupe) — no-SQL merging, dedupe and only-new-items across runs
- [HTTP Request Runner](https://apify.com/actor-forge/http-request-runner) — call APIs and collect JSON responses to query

### Changelog

- **2026-11-12** — Initial release: one read-only DuckDB query over Apify datasets (including the triggering run's dataset in integrations), CSV/TSV/JSON/JSONL/Parquet URLs and pasted rows; CSV/Parquet/JSONL result files.

***

*Built and maintained by **ActorForge**. Reliability first: every actor in the
portfolio is monitored by an automated nightly self-test, and breakages are
typically fixed the same day.*

# Actor input Schema

## `sql` (type: `string`):

One read-only DuckDB query: SELECT / WITH / FROM-first / PIVOT / SUMMARIZE / DESCRIBE, with joins, GROUP BY, window functions, QUALIFY, regexp\_\*, nested fields (address.city, tags\[1]) and json_extract. Tables: rows (pasted rows), dataset_1, dataset_2 … (or your names), file_1 … (or name=url); the first table is also called data. Quote column names with spaces: "Region Name". Writes, ATTACH, INSTALL/LOAD, settings and file/URL functions are refused.

## `rows` (type: `array`):

Optional rows pasted as a JSON array of objects (up to 100,000). Queried as the table rows.

## `datasetIds` (type: `array`):

Apify datasets to query (pick them, or pass dataset IDs via the API). In an integration that runs this Actor after another one, set this field to \["{{resource.defaultDatasetId}}"] to query the triggering run's results. Picking a dataset gives this run read access to it; nothing else on your account is readable. Each becomes a table: dataset_1, dataset_2 … or the names below.

## `datasetTableNames` (type: `array`):

Optional names for the datasets above, in the same order (e.g. jobs, companies). Letters, digits and \_.

## `fileUrls` (type: `array`):

Public file URLs, up to 200 MB each. Write name=https://… to choose the table name (e.g. countries=https://…/countries.csv). CSV delimiter and column types are detected; JSON may be an array, an object with an items/data/results array, or JSON Lines.

## `outputFiles` (type: `array`):

Optional. Writes the delivered rows as RESULT-csv / RESULT-parquet / RESULT-jsonl records in the run's key-value store (links in the OUTPUT record). Free.

## `maxResults` (type: `integer`):

Deliver at most this many result rows (the rest are not charged). A LIMIT in your SQL works too.

## `maxInputRows` (type: `integer`):

Stop loading sources after this many rows in total (a warning is logged; aggregates then cover only the loaded rows). Raise the run memory for many millions of rows.

## `queryTimeoutSecs` (type: `integer`):

Stop the query if it runs longer than this.

## Actor input object example

```json
{
  "sql": "SELECT category,\n       count(*) AS products,\n       round(avg(price), 2) AS avg_price,\n       max(rating) AS best_rating\nFROM rows\nGROUP BY category\nORDER BY products DESC, category",
  "rows": [
    {
      "sku": "A-100",
      "category": "shoes",
      "price": 89.9,
      "rating": 4.6
    },
    {
      "sku": "A-101",
      "category": "shoes",
      "price": 129,
      "rating": 4.2
    },
    {
      "sku": "B-200",
      "category": "jackets",
      "price": 199,
      "rating": 4.8
    },
    {
      "sku": "B-201",
      "category": "jackets",
      "price": 149.5,
      "rating": 3.9
    },
    {
      "sku": "B-202",
      "category": "jackets",
      "price": 99,
      "rating": 4.1
    },
    {
      "sku": "C-300",
      "category": "socks",
      "price": 12.5,
      "rating": 4.4
    }
  ],
  "outputFiles": [],
  "maxResults": 1000000,
  "maxInputRows": 2000000,
  "queryTimeoutSecs": 300
}
```

# Actor output Schema

## `results` (type: `string`):

The rows your SQL query returned (export as CSV, Excel, JSON, JSONL or XML from the dataset).

## `summary` (type: `string`):

The SQL, every table with its source, row count and column types, result columns, links to CSV/Parquet/JSONL files, billing.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "sql": `SELECT category,
       count(*) AS products,
       round(avg(price), 2) AS avg_price,
       max(rating) AS best_rating
FROM rows
GROUP BY category
ORDER BY products DESC, category`,
    "rows": [
        {
            "sku": "A-100",
            "category": "shoes",
            "price": 89.9,
            "rating": 4.6
        },
        {
            "sku": "A-101",
            "category": "shoes",
            "price": 129,
            "rating": 4.2
        },
        {
            "sku": "B-200",
            "category": "jackets",
            "price": 199,
            "rating": 4.8
        },
        {
            "sku": "B-201",
            "category": "jackets",
            "price": 149.5,
            "rating": 3.9
        },
        {
            "sku": "B-202",
            "category": "jackets",
            "price": 99,
            "rating": 4.1
        },
        {
            "sku": "C-300",
            "category": "socks",
            "price": 12.5,
            "rating": 4.4
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("actor-forge/dataset-sql-transform").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "sql": """SELECT category,
       count(*) AS products,
       round(avg(price), 2) AS avg_price,
       max(rating) AS best_rating
FROM rows
GROUP BY category
ORDER BY products DESC, category""",
    "rows": [
        {
            "sku": "A-100",
            "category": "shoes",
            "price": 89.9,
            "rating": 4.6,
        },
        {
            "sku": "A-101",
            "category": "shoes",
            "price": 129,
            "rating": 4.2,
        },
        {
            "sku": "B-200",
            "category": "jackets",
            "price": 199,
            "rating": 4.8,
        },
        {
            "sku": "B-201",
            "category": "jackets",
            "price": 149.5,
            "rating": 3.9,
        },
        {
            "sku": "B-202",
            "category": "jackets",
            "price": 99,
            "rating": 4.1,
        },
        {
            "sku": "C-300",
            "category": "socks",
            "price": 12.5,
            "rating": 4.4,
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("actor-forge/dataset-sql-transform").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "sql": "SELECT category,\\n       count(*) AS products,\\n       round(avg(price), 2) AS avg_price,\\n       max(rating) AS best_rating\\nFROM rows\\nGROUP BY category\\nORDER BY products DESC, category",
  "rows": [
    {
      "sku": "A-100",
      "category": "shoes",
      "price": 89.9,
      "rating": 4.6
    },
    {
      "sku": "A-101",
      "category": "shoes",
      "price": 129,
      "rating": 4.2
    },
    {
      "sku": "B-200",
      "category": "jackets",
      "price": 199,
      "rating": 4.8
    },
    {
      "sku": "B-201",
      "category": "jackets",
      "price": 149.5,
      "rating": 3.9
    },
    {
      "sku": "B-202",
      "category": "jackets",
      "price": 99,
      "rating": 4.1
    },
    {
      "sku": "C-300",
      "category": "socks",
      "price": 12.5,
      "rating": 4.4
    }
  ]
}' |
apify call actor-forge/dataset-sql-transform --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,actor-forge/dataset-sql-transform"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Ozga8XImt8OCDQqvL/builds/BIuPYvDjukyfqLQdh/openapi.json
