> For the complete documentation index, see [llms.txt](https://docs.slingdata.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.slingdata.io/connections/database-connections/duckdb.md). Agents can also search and read this documentation through its [MCP server](https://docs.slingdata.io/~gitbook/mcp).

# DuckDB

Connect & Ingest data from / to a DuckDB database

## Setup

The following credentials keys are accepted:

* `instance` **(required)** -> The local file path of the database file. For a remote DuckDB server, use `quack:<host>[:<port>]`. See [Quack](#quack-remote-duckdb-server).
* `schema` (optional) -> The default schema to use.
* `duckdb_version` (optional) -> The CLI version of DuckDB to use. The default is `2.0.0`. You can also specify the env. variable `DUCKDB_VERSION`.
* `storage_version` (optional *v1.6.7+*) -> The storage format version for a new database file, for example `v1.5.6`. Use it when a DuckDB older than 2.0 must read the file. Needs DuckDB 2.0 or later.
* `read_only` (optional) -> Whether to open the connection in `readonly` mode. Accepts `true` or `false`. Default is `false`.
* `interactive` (optional) -> Whether to communicate to the DuckDB CLI via interactive mode instead of reopening the connection each time. Accepts `true` or `false`. Default is `false`.
* `copy_format` (optional *v1.6.4+*) -> the data format that Sling uses to move data between Sling and DuckDB, for reads and writes. Acceptable values: `arrow`, `csv`. Default is `arrow`. Arrow needs the DuckDB `arrow` community extension. If DuckDB cannot load this extension (for example, with no internet access), Sling uses `csv`. **If you have issues with arrow, set `csv`**.
* `copy_method` (deprecated) -> use `copy_format`. `arrow_http` becomes `arrow`. All other values become `csv`.
* `max_buffer_size` (optional *v1.5*) -> the max buffer size to use when piping data from DuckDB CLI. Specify this if you have extremely large one-line text values in your dataset. Default is `10485760` (10MB).
* `max_line_size` (optional *v1.5.25+*) -> the max line size (in bytes) to use when piping CSV data into DuckDB. Sling raises this to `268435456` (256MB) when the data has string, text, json or binary columns, and uses `2000000` (2MB) otherwise. Specify this only if a single row is larger than 256MB.
* `use_adbc` (optional) -> Enable Arrow Database Connectivity (ADBC) driver for high-performance data transfer. See [ADBC](https://docs.slingdata.io/connections/database-connections/adbc.md) for setup and details. (*v1.5.2+*)
* `adbc_uri` (optional) -> Override the automatically constructed ADBC connection URI when using `use_adbc=true`.
* `timezone` (optional *v1.6.8+*) -> The time zone of the DuckDB session. Default is `UTC`. Sling sets it with `SET TimeZone`, so a timestamp does not shift by the time zone of the machine. Use an IANA name, for example `America/Sao_Paulo`. The value changes how DuckDB casts `TIMESTAMPTZ` to `TIMESTAMP`.

### Using `sling conns`

Here are examples of setting a connection named `DUCKDB`. We must provide the `type=duckdb` property:

{% code overflow="wrap" %}

```bash
# for local files 
$ sling conns set DUCKDB type=duckdb instance=/path/to/file.db

# for local files (Windows), don't use backslash (\)
$ sling conns set DUCKDB type=duckdb instance=C:/path/to/file.db

# Or use url (only for local files)
$ sling conns set DUCKDB url="duckdb:///path/to/file.db"

# url for Windows, don't use backslash (\)
$ sling conns set DUCKDB url="duckdb://C:/path/to/file.db"
```

{% endcode %}

### Environment Variable

See [here](https://docs.slingdata.io/pages/eAdVs2BHCgdr6RS8GoJC#dot-env-file-.env.sling) to learn more about the `.env.sling` file.

{% code overflow="wrap" %}

```bash
export DUCKDB='duckdb:///path/to/file.db'
export DUCKDB='{ type: duckdb, instance: "/path/to/file.db" }'

$env:DUCKDB="duckdb://C:/path/to/file.db" # for Windows PowerShell
```

{% endcode %}

### Sling Env File YAML

See [here](https://docs.slingdata.io/pages/eAdVs2BHCgdr6RS8GoJC#sling-env-file-env.yaml) to learn more about the sling `env.yaml` file.

```yaml
connections:
  DUCKDB:
    type: duckdb
    instance: <instance>
    schema: <schema>
    duckdb_version: '<duckdb_version>'
```

### Specifying a DuckDB version

By default, Sling downloads the DuckDB binary automatically. From *v1.6.7*, the default version is `2.0.0`. To use a different version, specify it this way, and Sling downloads that version:

```bash
export DUCKDB_VERSION='1.5.5'
```

You can also set `duckdb_version` on the connection.

### DuckDB 2.0 notes

{% hint style="warning" %}
DuckDB 2.0 writes new database files with a new storage format. DuckDB versions older than 2.0 cannot open these files. They give the error `created with an newer version of DuckDB`. If an older client must read the file, set `storage_version` (for example `v1.5.6`) before Sling makes the file, or set `duckdb_version: 1.5.5`.
{% endhint %}

DuckDB 2.0 changes some SQL behavior. Check your `sql` hooks, `pre_sql`, `post_sql` and custom queries:

* Lambda functions use the `lambda x: x + 1` syntax. The arrow syntax (`x -> x + 1`) gives the error `Deprecated lambda arrow (->) detected`.
* When a statement in a `BEGIN ... COMMIT` block fails, DuckDB aborts the transaction.
* The `~` operator does a partial match. Before 2.0, it did a full match. Use `regexp_full_match` for a full match.
* `CREATE TABLE ... AS SELECT NULL` gives a column of the `NULL` type. Cast the value to set a type, for example `NULL::VARCHAR`.
* `MERGE INTO` gives an error when the source has more than one row for the same key. Remove the duplicate keys from the source.

### Specifying a DuckDB Binary Path & Extensions

If you already have DuckDB on your machine and would like to use it (instead of having Sling download it), you can specify the binary path this way:

```bash
export DUCKDB_PATH='/opt/homebrew/bin/duckdb'
export DUCKDB_USE_INSTALLED_EXTENSIONS='true'  # tells sling not to download extensions
```

## Quack (remote DuckDB server)

From *v1.6.7*, Sling can connect to a remote DuckDB server through the Quack protocol of DuckDB 2.0. Use the `duckdb` type with an `instance` of the form `quack:<host>[:<port>]`. The default port is `9494`.

Start the server with the DuckDB CLI:

```bash
# serve a database file
duckdb my.db -serve

# or from SQL, with a token
duckdb my.db -c "CALL quack_serve('quack:localhost', token = 'my-secret-token')"
```

Then set the connection in `env.yaml`:

```yaml
connections:
  DUCKDB_REMOTE:
    type: duckdb
    instance: quack:db-host:9494
    token: ${QUACK_TOKEN}
    schema: main
```

Or with the URL:

```bash
sling conns set DUCKDB_REMOTE url="duckdb://quack:db-host:9494" token=my-secret-token
```

These properties apply to a Quack connection:

| Property             | Description                                                                                                                |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `instance`           | **(required)** The server URI, `quack:<host>[:<port>]`.                                                                    |
| `token`              | The token of the server. Sling keeps it in a DuckDB secret.                                                                |
| `database`           | The local alias of the remote catalog. Default is `quack`.                                                                 |
| `schema`             | The default schema. Default is `main`.                                                                                     |
| `read_only`          | Attach the server in read-only mode. DuckDB 2.0.0 does not enforce it on the server, so also use a token with read access. |
| `disable_ssl`        | Set `true` to connect without TLS.                                                                                         |
| `ssl_fingerprint`    | The certificate fingerprint to accept, for a self-signed certificate.                                                      |
| `client_id`          | The client name that the server shows.                                                                                     |
| `heartbeat_timeout`  | The heartbeat timeout, in seconds.                                                                                         |
| `extra_http_headers` | A JSON object of extra HTTP headers, for example `{"X-Team": "data"}`.                                                     |

**TLS**: bind the server to `localhost` and put it behind a reverse proxy with TLS. Use the proxy port in the URI. For a self-signed certificate, set `ssl_fingerprint`.

**Concurrency**: many Sling runs can write to the same server at the same time. There is no file lock. Sling gives each staging table a random suffix, so the runs do not collide.

**Limits**:

* Both the server and Sling must use DuckDB 2.0 or later. With an older `duckdb_version`, the connection fails.
* The Quack protocol is new and is not yet stable. A new DuckDB version can change it.
* The server cannot make indexes. Sling skips `table_keys.index` and logs a warning.
* One query can scan only one remote table.

## Geometry Data

Sling types PostGIS `geometry`, MySQL and MariaDB spatial columns, and BigQuery `geography` as `geometry`. When you load into a DuckDB table, Sling creates the column with the native `GEOMETRY` type. The `spatial` extension loads automatically. Available from *v1.5.27*.

If the target table already exists and the column is `VARCHAR`, Sling keeps that type. The value then stays WKB hex text. Convert it after the load:

```sql
select st_geomfromwkb(unhex(location)) as location from my_table;
```

When you export to Parquet files, Sling writes these columns as native `GEOMETRY` as well. Each file also carries the GeoParquet `geo` metadata. WKB does not carry a CRS, so set the `geometry_crs` property on the target file connection to stamp a CRS such as `EPSG:4326` into that metadata. See the [PostGIS Geometry](https://docs.slingdata.io/connections/database-connections/postgres.md#postgis-geometry) section for details.

If you are facing issues connecting, give [`sling assist`](https://docs.slingdata.io/sling-cli/ai/assist.md) a try, or reach out to us at <support@slingdata.io>, on [discord](https://discord.gg/q5xtaSNDvp) or open a Github Issue [here](https://github.com/slingdata-io/sling-cli/issues).

### Potential Issue

If you have a `.duckdbrc` file, which runs commands whenever the DuckDB CLI is invoked, this may interfere with normal Sling operation. If you are facing weird issues and have this file, try again after deleting it.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.slingdata.io/connections/database-connections/duckdb.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
