Speaking other SQL dialects to DuckDB with the polyglot extension

Speaking other SQL dialects to DuckDB with the polyglot extension

10 min read

Load the polyglot extension, select a dialect, and DuckDB executes T-SQL, MySQL, PostgreSQL, BigQuery or Snowflake SQL as it is. No function call around the query, no rewrite in the application.

In February I introduced polyglot, a Rust library that transpiles SQL between dialects. The DuckDB polyglot extension brings that library into DuckDB. Until now it worked through functions: you passed your SQL as a string to polyglot_transpile() or polyglot_query(), together with the dialect it was written in.

Version 0.7.0 removes the string. A connection can now declare an input dialect, and from then on every statement it sends is translated to DuckDB SQL inside DuckDB’s parser and executed right away:

INSTALL AND LOAD polyglot FROM tobilg;
SET SESSION allow_parser_override_extension = 'strict';
SET SESSION polyglot_input_dialect = 'tsql';

SELECT TOP 2 n FROM (VALUES (3), (1), (2)) AS t(n) ORDER BY n;
┌───┐
│ n │
├───┤
│ 1 │
│ 2 │
└───┘

That’s T-SQL, typed into a DuckDB shell. This post covers:

  • Why I think this is a big deal for migrations, tests and tools.
  • How to install the extension and select a dialect.
  • Working examples in six dialects against the same table.
  • What “same semantics” means, with cases where the same text gives a different answer.
  • Prepared statements from Python, transactions, and remote use over Quack.
  • The limits, and what I haven’t tested.

Every example below ran on DuckDB v2.0.1 with polyglot v0.7.0. The reference is the input dialects guide, and the internals are described in the architecture notes.

Why this is useful#

A function like polyglot_query('SELECT TOP 2 ...', 'tsql') is fine in a notebook. It doesn’t help when the SQL lives somewhere you can’t easily change: in an application, an ORM, a BI tool, a folder of 400 report queries. There, the SQL isn’t a string you hold in your hand. It’s whatever the client sends.

With an input dialect, the translation moves to the one place every statement has to pass anyway, which is DuckDB’s parser. That has a few consequences I really like:

  • It works with every client. The CLI, Python, JDBC, Node.js, or anything else that can open a DuckDB connection. The application keeps its driver and its database path or URL. The only addition is two SET statements after connecting.
  • Migrations get much cheaper to try. You can point an existing SQL Server or MySQL workload at DuckDB and see what runs, before rewriting a single query.
  • Tests can run locally. Queries written for Snowflake or BigQuery can run against a local DuckDB file in CI, without a warehouse and without credentials.
  • You can keep writing the dialect you know. If your fingers type ISNULL and TOP, that’s fine now.
  • One engine for mixed sources. Different connections can speak different dialects to the same database at the same time.

The extension doesn’t just swap keywords, either. It tries to keep what a statement means in its dialect, which matters more than it sounds. More on that below.

Installing the extension#

You need DuckDB v2.0.1. The extension hooks into DuckDB’s C++ parser API, so each build only loads into the exact DuckDB version it was built for.

Version 0.7.0 is published in my own extension repository, signed with my own key. I described how that works in Hosting your own signed DuckDB extensions. You register the repository once, then install and load by repository name:

SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS tobilg
    WITH PREFIX 'https://extensions.duckdb.tobilg.com';

INSTALL AND LOAD polyglot FROM tobilg;

The community extension still serves an older build at the time of writing. Once the new version is published there, INSTALL polyglot FROM community followed by LOAD polyglot will work as well.

Selecting a dialect#

LOAD polyglot alone changes nothing about how a connection parses SQL. It only adds the functions and a setting. A connection opts in with two statements:

SET SESSION allow_parser_override_extension = 'strict';
SET SESSION polyglot_input_dialect = 'mysql';
SettingOwnerWhat it does
allow_parser_override_extensionDuckDBLets extensions take over parsing for this connection. Has to be 'strict' before a dialect can be selected.
polyglot_input_dialectpolyglotThe dialect this connection speaks. Empty, the default, means DuckDB SQL.

Both are per connection. An application or a connection pool runs them once, right after opening a connection. Send each of them as its own statement, not in a batch with other SQL.

The rest is what you’d expect:

You want toStatement
Switch to another dialectSET SESSION polyglot_input_dialect = 'postgresql';
See the current dialectSELECT current_setting('polyglot_input_dialect');
Go back to DuckDB SQLRESET polyglot_input_dialect;
List all 34 dialect namesSELECT * FROM polyglot_dialects(); (while speaking DuckDB SQL)

Aliases work too: 'mssql' and 'sqlserver' select tsql, 'postgres' selects postgresql. The setting always reads back the canonical name.

How it works#

An application sends T-SQL through its existing DuckDB driver. The polyglot parser hook translates the statement to DuckDB SQL if the connection has selected a dialect. DuckDB then parses, binds and executes it in the same session and transaction and returns rows with native DuckDB types.

DuckDB 2.0 lets an extension register a parser override. DuckDB offers each submitted statement to that override first, together with the connection it came from. polyglot’s override does one of three things:

  1. No dialect is selected on that connection: it declines, and DuckDB parses the statement as always.
  2. The statement is a SET or RESET of one of the two settings: it’s parsed natively, so you can always switch or leave a dialect.
  3. Otherwise the statement is translated to DuckDB SQL, the result is parsed with DuckDB’s own grammar, and DuckDB binds and executes it.

Statement text reaches polyglot's parser override first. Without a selected dialect, or for a lone SET or RESET of the two settings, the original text goes straight to DuckDB's PEG parser. Otherwise the Rust translation core turns it into DuckDB SQL, which DuckDB's unchanged PEG parser parses with the override switched off for that one parse. The resulting statements are bound, planned and executed in the same session.

The override doesn’t replace or modify DuckDB’s parser. It runs in front of it: the translated SQL goes through DuckDB’s own PEG parser, the same one that parses native DuckDB SQL, so everything after the translation is the regular DuckDB path. For that inner parse, the override is switched off, so the generated SQL is never offered to polyglot a second time.

The translation itself is the polyglot-sql Rust crate, linked statically into the extension. The entry point is C++, because the parser override only exists in DuckDB’s C++ API.

Two properties follow from this design:

  • It’s the same session. Nothing runs on a second connection. Temporary tables, transactions, settings and prepared statements behave exactly as if you had written DuckDB SQL.
  • Errors are never papered over. If a statement can’t be translated, it fails. The original text is never retried as DuckDB SQL, because that could silently return a different answer.

One table, six dialects#

Let’s create a small table in plain DuckDB SQL, before selecting any dialect:

CREATE TABLE orders AS
SELECT * FROM (VALUES
  (1, 'alice', DATE '2026-11-02', 120.00, 'shipped'),
  (2, 'bob',   DATE '2026-11-15',  35.50, 'open'),
  (3, 'alice', DATE '2026-11-28', 240.10, 'open'),
  (4, 'carol', DATE '2026-12-01',  18.90, NULL),
  (5, 'bob',   DATE '2026-12-04', 310.00, 'shipped')
) AS t(id, customer, order_date, amount, status);

SET SESSION allow_parser_override_extension = 'strict';

From here on, each block starts by switching the dialect.

T-SQL#

SET SESSION polyglot_input_dialect = 'tsql';

SELECT TOP 3 id, customer,
       ISNULL(status, 'unknown') AS status,
       DATEDIFF(day, order_date, '2026-12-06') AS age_days
FROM orders
ORDER BY amount DESC;
┌────┬──────────┬─────────┬──────────┐
│ id │ customer │ status  │ age_days │
├────┼──────────┼─────────┼──────────┤
│ 5  │ bob      │ shipped │ 2        │
│ 3  │ alice    │ open    │ 8        │
│ 1  │ alice    │ shipped │ 34       │
└────┴──────────┴─────────┴──────────┘

TOP, ISNULL and the three-argument DATEDIFF with an unquoted date part are all not DuckDB SQL.

MySQL#

SET SESSION polyglot_input_dialect = 'mysql';

SELECT customer,
       GROUP_CONCAT(id ORDER BY id SEPARATOR '-') AS ids,
       DATE_FORMAT(MAX(order_date), '%d.%m.%Y') AS last_order
FROM orders
GROUP BY customer
ORDER BY customer
LIMIT 1, 2;
┌──────────┬─────┬────────────┐
│ customer │ ids │ last_order │
├──────────┼─────┼────────────┤
│ bob      │ 2-5 │ 04.12.2026 │
│ carol    │ 4   │ 01.12.2026 │
└──────────┴─────┴────────────┘

Note the LIMIT 1, 2: MySQL puts the offset first, so this skips one row and returns two.

PostgreSQL#

SET SESSION polyglot_input_dialect = 'postgresql';

SELECT customer,
       string_agg(id::text, ',' ORDER BY id) AS ids,
       sum(id) / count(*) AS avg_id
FROM orders
GROUP BY customer
ORDER BY customer;
┌──────────┬─────┬────────┐
│ customer │ ids │ avg_id │
├──────────┼─────┼────────┤
│ alice    │ 1,3 │ 2      │
│ bob      │ 2,5 │ 3      │
│ carol    │ 4   │ 4      │
└──────────┴─────┴────────┘

PostgreSQL is close to DuckDB, so this query would also parse without polyglot. The result wouldn’t be the same, though: bob’s avg_id would be 3.5. See the next section.

Snowflake#

SET SESSION polyglot_input_dialect = 'snowflake';

SELECT customer,
       IFF(SUM(amount) > 200, 'big', 'small') AS segment,
       TO_CHAR(MAX(order_date), 'YYYY-MM-DD') AS last_order,
       NVL(MAX(status), 'n/a') AS status
FROM orders
GROUP BY customer
ORDER BY customer;
┌──────────┬─────────┬────────────┬─────────┐
│ customer │ segment │ last_order │ status  │
├──────────┼─────────┼────────────┼─────────┤
│ alice    │ big     │ 2026-11-28 │ shipped │
│ bob      │ big     │ 2026-12-04 │ shipped │
│ carol    │ small   │ 2026-12-01 │ n/a     │
└──────────┴─────────┴────────────┴─────────┘

BigQuery#

SET SESSION polyglot_input_dialect = 'bigquery';

SELECT * EXCEPT (status)
FROM `orders`
WHERE order_date >= DATE_SUB(DATE '2026-12-06', INTERVAL 7 DAY);
┌────┬──────────┬────────────┬────────┐
│ id │ customer │ order_date │ amount │
├────┼──────────┼────────────┼────────┤
│ 4  │ carol    │ 2026-12-01 │ 18.90  │
│ 5  │ bob      │ 2026-12-04 │ 310.00 │
└────┴──────────┴────────────┴────────┘
SELECT customer,
       COUNTIF(amount > 100) AS big_orders,
       FORMAT_DATE('%Y-%m', MAX(order_date)) AS last_month
FROM orders
GROUP BY customer
ORDER BY customer;
┌──────────┬────────────┬────────────┐
│ customer │ big_orders │ last_month │
├──────────┼────────────┼────────────┤
│ alice    │ 2          │ 2026-11    │
│ bob      │ 1          │ 2026-12    │
│ carol    │ 0          │ 2026-12    │
└──────────┴────────────┴────────────┘

Spark#

SET SESSION polyglot_input_dialect = 'spark';

SELECT customer,
       collect_list(id) AS ids,
       date_format(max(order_date), 'yyyy-MM-dd') AS last_order
FROM orders
GROUP BY customer
ORDER BY customer;
┌──────────┬────────┬────────────┐
│ customer │  ids   │ last_order │
├──────────┼────────┼────────────┤
│ alice    │ [1, 3] │ 2026-11-28 │
│ bob      │ [2, 5] │ 2026-12-04 │
│ carol    │ [4]    │ 2026-12-01 │
└──────────┴────────┴────────────┘

When you’re done:

RESET polyglot_input_dialect;

Same text, different answer#

The interesting cases aren’t the ones DuckDB rejects. They’re the ones DuckDB accepts and answers differently. That’s why every statement goes through the translation once a dialect is selected, including the ones that are valid DuckDB SQL already.

StatementPlain DuckDBWith the dialect selected
SELECT TRUE || FALSEtruefalse (string concatenation)true in MySQL (logical OR)
SELECT 5 / 22.52 in PostgreSQL (integer division)
SELECT 5.0 / 22.52.5 in PostgreSQL
ORDER BY n with NULLsNULLs lastNULLs first in MySQL and T-SQL

The division is my favourite one, because it can’t be solved by rewriting text. In PostgreSQL, T-SQL, SQLite, Redshift and a few others, / between two integers is an integer division. In DuckDB, / is always fractional. For a / b on two columns, the translator doesn’t know the types, so it can’t pick between DuckDB’s // and /.

The extension solves this with a helper. The generated SQL calls polyglot_typed_division(a, b), and DuckDB replaces that call with // or / while binding, once the operand types are known. It works for parameters too, whose types are only known at execution. You’ll see the function name in EXPLAIN output, but it’s not meant to be called directly.

The explicit functions differ on purpose here: polyglot_query(sql, dialect) executes with the same semantics as a session in that dialect, while polyglot_transpile(sql, dialect) stays a plain text-to-text translation.

Seeing the generated SQL#

If you want to know what DuckDB actually runs, there are two easy ways. In the CLI, .echo on prints the translated statement instead of the one you typed:

.echo on
SET SESSION polyglot_input_dialect = 'mysql';
SELECT `n` FROM (SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3) t ORDER BY n LIMIT 1, 2;
SELECT "n" FROM (SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3) AS t ORDER BY n NULLS FIRST LIMIT 2 OFFSET 1

Backticks became double quotes, the LIMIT arguments were reordered, and NULLS FIRST was added to keep MySQL’s sort order.

The other way works from any client, while speaking DuckDB SQL:

SELECT polyglot_transpile(
  'SELECT TOP 3 id, ISNULL(status, ''unknown'') FROM orders ORDER BY amount DESC',
  'tsql'
) AS duckdb_sql;
SELECT id, COALESCE(status, 'unknown') FROM orders ORDER BY amount DESC LIMIT 3

Prepared statements#

Parameters go through DuckDB’s normal prepare and bind API. Values are bound, and they never become part of the SQL text. Here’s a Python script against the same orders table:

import duckdb

con = duckdb.connect("orders.db")
con.execute("LOAD polyglot FROM tobilg")
con.execute("SET SESSION allow_parser_override_extension = 'strict'")

# MySQL: offset first, then row count
con.execute("SET SESSION polyglot_input_dialect = 'mysql'")
con.execute("SELECT id, customer FROM orders ORDER BY id LIMIT ?, ?", [1, 2]).fetchall()
# [(2, 'bob'), (3, 'alice')]

# T-SQL: a parameter inside TOP
con.execute("SET SESSION polyglot_input_dialect = 'tsql'")
con.execute(
    "SELECT TOP (?) id, amount FROM orders WHERE amount > ? ORDER BY amount DESC", [2, 100]
).fetchall()
# [(5, Decimal('310.00')), (3, Decimal('240.10'))]

# PostgreSQL: numbered parameters, and the division follows the bound types
con.execute("SET SESSION polyglot_input_dialect = 'postgresql'")
con.execute("SELECT $2 / $1 AS q", [2, 7]).fetchall()     # [(3,)]
con.execute("SELECT $2 / $1 AS q", [2, 7.0]).fetchall()   # [(3.5,)]

# BigQuery: named parameters
con.execute("SET SESSION polyglot_input_dialect = 'bigquery'")
con.execute(
    "SELECT id FROM orders WHERE customer = @c OR status = @s ORDER BY id",
    {"c": "carol", "s": "open"},
).fetchall()
# [(2,), (3,), (4,)]

The MySQL case is the tricky one. The translation has to swap the two LIMIT arguments, and the parameters keep their identity when it does: [1, 2] still means “skip one, return two”.

One thing to know: cursors created with con.cursor() are separate sessions. Each one needs its own two SET statements and can use a different dialect.

T-SQL and MySQL @variables are not supported. They fail with a clear message instead of being translated wrongly:

Parser Error: polyglot could not translate this tsql statement to DuckDB SQL:
Unsupported: tsql variable @id has no DuckDB equivalent; use a positional '?' parameter instead

It’s the same session#

Because the translated statement runs on the connection that sent it, transactions and temporary tables just work:

SET SESSION polyglot_input_dialect = 'postgresql';

BEGIN;
CREATE TEMP TABLE big AS SELECT * FROM orders WHERE amount > 100;
SELECT count(*) FROM big;   -- 3
ROLLBACK;

SELECT count(*) FROM big;   -- Catalog Error: Table with name big does not exist!

Remote use over Quack#

Quack is DuckDB’s own client/server protocol. A Quack client forwards its statements as text, and the server executes them on a server-side session. That’s exactly where the parser hook sits, so the translation happens on the server and the clients don’t need polyglot at all.

On the server:

LOAD polyglot FROM tobilg;
CALL quack_serve('quack:localhost:9494', token = 'super_secret');

On the client, a stock DuckDB:

ATTACH 'quack:localhost:9494' AS remote (TOKEN 'super_secret');
CONNECT remote;

-- from here on, every statement runs on the server
SET SESSION allow_parser_override_extension = 'strict';
SET SESSION polyglot_input_dialect = 'tsql';
SELECT TOP 2 id, customer FROM orders ORDER BY amount DESC;

DISCONNECT;
-- local DuckDB again, with DuckDB semantics

The order matters. The two SET statements have to come after CONNECT, so that they configure the session on the server. Each connected client has its own server session, so different clients can speak different dialects at the same time.

To be clear about what this is not: PostgreSQL, MySQL and T-SQL are input SQL dialects here. Their wire protocols are not implemented, so psql or a SQL Server driver can’t connect.

Safeguards#

A setup that can’t take effect should be an error, not foreign SQL quietly running as DuckDB SQL. The extension is strict about that:

  • Selecting a dialect fails unless allow_parser_override_extension is 'strict' on that connection. 'fallback' is refused too, because it would let DuckDB run statements that polyglot rejected.
  • While a dialect is selected, allow_parser_override_extension can’t be changed. Reset the dialect first.
  • SET GLOBAL polyglot_input_dialect is rejected. Every connection opts in for itself.

The error messages say what to do:

Invalid Input Error: Cannot select input dialect 'mysql': this connection does not let parser
extensions take over. Run SET SESSION allow_parser_override_extension = 'strict' on this connection first.

Limits, and what I haven’t tested#

  • Coverage is that of polyglot-sql. Not every function of every dialect has a DuckDB translation. In my tests, T-SQL’s FORMAT(x, 'N2') and CONVERT with a style number, Oracle’s ROWNUM and ClickHouse’s uniqExact came through untranslated and failed in DuckDB with a binder or catalog error. So try your own queries before you rely on it.
  • The parsers are lenient in places. With mysql selected, PRAGMA version and a DuckDB list literal still ran. A statement that isn’t strictly valid in the selected dialect may be accepted anyway, so this isn’t a validator for the source dialect.
  • It’s translation, not emulation. There are no system catalogs like information_schema in SQL Server’s flavour, no stored procedures, and no T-SQL or MySQL session variables.
  • One DuckDB version per build. v0.7.0 loads into DuckDB v2.0.1 and nothing else.
  • Not tested by me: JDBC and other clients besides the CLI and Python. They use DuckDB’s regular prepare path, so I expect them to work, but I haven’t run them. The same goes for large real-world workloads.

If you hit a statement that translates wrongly or not at all, please open an issue in polyglot or the extension repo.

Summary#

With polyglot v0.7.0, DuckDB can be spoken to in 33 other SQL dialects. A connection runs two SET statements, and from then on its T-SQL, MySQL, PostgreSQL, Snowflake, BigQuery or Spark statements are translated inside DuckDB’s parser and executed in the same session, with prepared statements, transactions and the source dialect’s semantics for things like integer division.

For me, the best part is how little it asks of the client: the same driver, the same database, the SQL you already have. The source code is on GitHub, and the input dialects guide has the full reference, including batches and all error messages.