

 Amazon Redshift will no longer support the use of Python UDFs after June 30, 2026. We will start enforcing it in phases. For more information on the details of Python end of life and migration options, see the [ blog post ](https://aws.amazon.com/blogs/big-data/amazon-redshift-python-user-defined-functions-will-reach-end-of-support-after-june-30-2026/) that was published on June 30, 2025. 

# Running queries with `redshift_query`

The extension adds one table function.

```sql
redshift_query(handle VARCHAR, sql VARCHAR [, params := LIST(VARCHAR)])
```

The function runs `sql` on Redshift through the handle and returns the result as a DuckDB table. Redshift runs the statement as written, and DuckDB does not translate it.

A statement with no result set, such as DML, DDL, or `SET`, returns one column, `rowcount BIGINT`, which is the number of rows the statement affected. It is `NULL` when no count is available, and `SET` and DDL such as `CREATE TABLE` report `0`. A query whose result has no rows returns an empty table with its columns. Each call runs one statement. The Redshift refuses a string with several statements, with SQLSTATE `42601` (`cannot insert multiple commands into a prepared statement`), or a statement that returns more than one result set.

The `params` argument binds values to `$1`, `$2`, and so on, in order. The extension never pastes them into the SQL text. Each value is a string. Cast it in the Redshift SQL where Redshift can't infer the type you need, for example `$2::date`. The extension refuses a `NULL` element or a `NULL` list, so write `NULL` in the SQL instead.

```sql
SELECT * FROM redshift_query('rs', 'SELECT o_orderkey, o_totalprice FROM tpch.orders ORDER BY 1 LIMIT 3');

SELECT * FROM redshift_query('rs',
  'SELECT o_orderkey, o_orderstatus FROM tpch.orders WHERE o_orderstatus = $1 AND o_orderdate = $2::date ORDER BY 1 LIMIT 5',
  params := ['F', '1994-01-01']);
```

## Usage rules
<a name="duckdb-redshift-querying-rules"></a>
+ **One call for each handle for each DuckDB statement**. Each handle has one Redshift connection for each DuckDB connection, so one DuckDB statement can use a handle only once. Two different handles in one statement are fine. To use one target twice, attach it under two handles, or stage one result in a DuckDB temporary table first.
+ **Not inside a DuckDB transaction**. The extension refuses `redshift_query` while an explicit DuckDB transaction is open.
+ **Not in recursive CTEs or open PIVOTs**. The extension refuses it in the recursive part of a recursive CTE, as the source of a `PIVOT` without an `IN` list, and in the subquery of a `PIVOT`'s `IN (subquery)`.
+ **One streaming statement per handle**. Although a result is still streaming on a handle, the extension refuses another call on that handle from the same DuckDB connection.
+ If a column's type changes between when DuckDB prepares the query and when it runs, the call fails. The statement might have run, so check a write's effects before you run it again.

**Warning**  
`sql` runs on Redshift with every privilege of the handle's database user. Never build it by concatenating user input. Pass values with `params`, and check any identifier or SQL fragment you insert against a fixed list. The one-statement rule does not make concatenated input safe.

**Warning**  
A write can take effect even when the call fails. Once a statement has started to run, a later failure, such as a lost connection or a value outside DuckDB's range, can leave its effects committed. Check the target before you run a failed write again.

## Writing the Redshift SQL
<a name="duckdb-redshift-querying-writing"></a>

The Redshift SQL is a DuckDB string, so double every single quote inside it, or use a dollar-quoted string:

```sql
SELECT * FROM redshift_query('rs', 'SELECT * FROM tpch.orders WHERE o_orderdate >= DATE ''1998-07-01''');
SELECT * FROM redshift_query('rs', $$SELECT * FROM tpch.orders WHERE o_orderdate >= DATE '1998-07-01'$$);
```

A `LIMIT`, filter, or aggregation that you write in DuckDB applies after Redshift has sent the rows. Put this work in the Redshift SQL so that Redshift reduces the data first.

Write no `?` in the SQL text, with or without `params`. The embedded driver rewrites each `?` it finds into a parameter marker before Redshift sees it, even inside a dollar-quoted string, so `SELECT $$colou?r$$` returns `colou$1r`. Use `$1`, `$2`, and so on for parameters and `chr(63)` for a literal question mark, and pass untrusted values through `params` rather than in the SQL text.

## Finding databases, schemas, and tables
<a name="duckdb-redshift-querying-catalogs"></a>

The handle is not a browsable DuckDB catalog, so `SELECT * FROM rs.schema.table` is refused. List what Redshift holds through Redshift commands and system views, run through `redshift_query`:

```sql
SELECT * FROM redshift_query('rs', 'SHOW DATABASES');
SELECT * FROM redshift_query('rs', 'SHOW SCHEMAS FROM DATABASE dev');
SELECT * FROM redshift_query('rs', 'SHOW TABLES FROM SCHEMA dev.public');
```

A query on one database can read another through Redshift three-part names, `"<database>"."<schema>"."<table>"`. Where the workgroup or cluster auto-mounts the AWS Glue Data Catalog, `SHOW DATABASES` lists its catalogs as `auto mounted catalog`, and you read them the same way.


| Catalog | Three-part name | 
| --- | --- | 
| The AWS Glue Data Catalog | `awsdatacatalog."<glue database>"."<table>"` | 
| An Amazon S3 table bucket | `"<table bucket>@s3tablescatalog"."<namespace>"."<table>"` | 
| A database of another Redshift warehouse registered in the Data Catalog | `"<database>@<catalog>"."<schema>"."<table>"` | 

```sql
SELECT * FROM redshift_query('rs',
  'SELECT count(*) FROM "my-table-bucket@s3tablescatalog".my_namespace.my_table');
```

Connect to a local database such as `dev` and use these names. `DATABASE` can't name a catalog that `SHOW DATABASES` lists with `allow_connections` set to false, such as `awsdatacatalog`; connecting then fails with SQLSTATE `55000`. A catalog that `SHOW DATABASES` doesn't list fails with SQLSTATE `3D000`. Reading an auto-mounted catalog needs the Redshift and AWS Lake Formation grants that the Redshift documentation describes.

## Sessions and transactions
<a name="duckdb-redshift-querying-sessions"></a>

Each pair of handle and DuckDB connection has at most one Redshift session. The attach opens it for the DuckDB connection that runs it, and later calls reuse it. Session state, such as temporary tables, `SET` values, and open Redshift transactions, lasts until the session ends. Other DuckDB connections, such as Python cursors or threads, get their own sessions. Sessions end on `DETACH`, when the DuckDB connection closes, or when Redshift ends them, such as when Redshift Serverless ends a session that is idle for 3,600 seconds (1 hour).

Each connection sets the session to UTC, date style `ISO, MDY`, interval style `postgres`, and full float output, so values arrive in one form. Don't change these through `redshift_query`, because the extension relies on them when it reads values.

Autocommit is on, so each statement commits on its own. To group statements into a Redshift transaction, run `BEGIN` and `COMMIT` through `redshift_query` on the same handle and DuckDB connection:

```sql
SELECT * FROM redshift_query('rs', 'BEGIN');
SELECT * FROM redshift_query('rs', 'INSERT INTO sales.audit SELECT * FROM sales.staging');
SELECT * FROM redshift_query('rs', 'DELETE FROM sales.staging');
SELECT * FROM redshift_query('rs', 'COMMIT');
```

A lost connection, or the error that says the session can't be used any more, ends the session and rolls back its open transaction. The statements after it run in a new session, each committing on its own, so a script can commit half its work. To stop a script at that point, run it with the DuckDB shell's `-bail` option.

A DuckDB transaction can't control what Redshift did, so the extension refuses `redshift_query` while an explicit DuckDB transaction is open. Run it in autocommit mode. After the connection to Redshift is lost during a run, the extension never replays the statement, because a write it carried might already have taken effect. Check the target before you run it again. The extension retries a connect while an idle Redshift Serverless workgroup resumes.

After an error inside a Redshift transaction, Redshift refuses every statement with SQLSTATE `25P02` until the transaction ends. The statement that fails first can also report `25P02` instead of its own error. To see the cause, run `ROLLBACK`, then run the statement again outside the transaction. Run `ROLLBACK` to end it; the work in it is lost, and a `COMMIT` rolls it back too.

To run `redshift_query` inside an explicit DuckDB transaction anyway, set `redshift_allow_query_in_duckdb_transaction` to `true`. A DuckDB `ROLLBACK` then doesn't undo the Redshift work, and the extension still refuses a call on a handle the open transaction attached. For more information, see [Settings](duckdb-redshift-settings.md).

```sql
SET redshift_allow_query_in_duckdb_transaction = true;
BEGIN;
SELECT * FROM redshift_query('rs', 'SELECT 1');
COMMIT;
```

## Cancelling a statement
<a name="duckdb-redshift-querying-cancellation"></a>

**Warning**  
Statements can't be cancelled from DuckDB, and there is no statement timeout. After you press Ctrl-C, the statement keeps running on Redshift until it completes.

To stop a running statement, cancel it from another session. Get the session's process ID, then cancel it from another DuckDB connection or any Redshift client:

```sql
-- Before the long statement, on the handle that will run it:
SELECT * FROM redshift_query('rs', 'SELECT pg_backend_pid()');
-- From another DuckDB connection or process, with its own handle:
SELECT * FROM redshift_query('rs_other', 'SELECT pg_cancel_backend({{pid}})');
```

Redshift's own `statement_timeout`, set with `SET` through `redshift_query`, applies to the rest of that session.

## Large results
<a name="duckdb-redshift-querying-large-results"></a>

Rows stream from Redshift in batches while DuckDB processes them, fetched up to four batches ahead with fetch buffers of about 16 MiB, so DuckDB holds only what the query keeps. Do the filtering and aggregation in the Redshift SQL so that only the rows you need cross the network.

A streamed result passes through, and the extension doesn't save it after you read it. To keep a large result, read it once and store it locally. To keep it as a DuckDB table that you can query again, use `CREATE TABLE ... AS`, which runs the query on Redshift and fills a new local table with the returned rows:

```sql
CREATE TABLE venues AS SELECT * FROM redshift_query('rs', 'SELECT * FROM venue');
```

To write the result to a local file instead, use `COPY ... TO`, which streams the rows straight to a Parquet file on disk:

```sql
COPY (SELECT * FROM redshift_query('rs', 'SELECT * FROM sales')) TO 'sales.parquet' (FORMAT parquet);
```

One `redshift_query` call reads its result on one connection. To load a large table faster, split it into disjoint ranges of a key and read each range with its own call on its own DuckDB connection, running at the same time, into one table you create first:

```sql
-- Create the destination table once, before the parallel reads.
CREATE TABLE sales_copy AS SELECT * FROM redshift_query('rs', 'SELECT * FROM sales LIMIT 0');

-- On each DuckDB connection, with its own range:
INSERT INTO sales_copy
  SELECT * FROM redshift_query('rs', 'SELECT * FROM sales WHERE salesid >= 0 AND salesid < 50000000');
```

Run no more of these parallel reads at once than the workgroup or cluster can run at the same time. Any beyond that wait in line and add no speed. This technique doesn't work for a query that uses `ORDER BY` or `LIMIT`. A global sort has to see every row to order it, and a row limit applies to the whole result, so neither can be divided into independent ranges. Run those as a single call, and sort in DuckDB after the data lands. Don't combine the slices with `UNION ALL` in one statement, even on separate handles, because DuckDB runs the branches one after another.

A query that binds no `params` and returns no `REAL`, `DOUBLE PRECISION`, or interval columns reads on a faster internal path.