How to Join Tables from Different Databases: PostgreSQL, MySQL, MariaDB and ClickHouse
You can join tables from different databases in one SQL query. The method depends on whether the tables live in the same database engine on the same server. If they do, it is often a one-line change. If they don't, for example users in MariaDB and payments in ClickHouse, you need something that can talk to both engines: a foreign data wrapper, a table function, an embedded engine like DuckDB, or a federated query engine.
This guide walks through six working methods, with SQL you can copy, and tells you when each one stops being a good idea.
On this page
- What a cross-database join is, and why it is harder than a normal JOIN
- Method 1: Same server — qualified table names
- Method 2: PostgreSQL cross-database query with postgres_fdw or dblink
- Method 3: ClickHouse table functions mysql() and postgresql()
- Method 4: DuckDB ATTACH for ad-hoc analysis
- Method 5: A federated query engine
- Method 6: Join in application code, or copy everything with ETL
- Step by step: join MariaDB, PostgreSQL and ClickHouse in one query with Otterstax
- Performance: what makes cross-database joins slow, and how to avoid it
- FAQ
- Next step
Quick answer: which method fits your case
| Your situation | Use | Setup effort |
|---|---|---|
| Two databases on the same MySQL / MariaDB / SQL Server instance | Qualified names: db.table (MySQL), db.schema.table (SQL Server) |
None |
| Two PostgreSQL databases | postgres_fdw or dblink |
Low: one extension |
| PostgreSQL + MySQL, occasional queries | postgres_fdw + mysql_fdw, or DuckDB ATTACH |
Low to medium |
| Analytics in ClickHouse that needs rows from MySQL / PostgreSQL | ClickHouse mysql() / postgresql() table functions |
Low |
| A one-off investigation on your laptop | DuckDB with postgres and mysql extensions |
Low |
| Production apps, dashboards or AI agents that join 2+ engines every day | Federated query engine (Trino, Otterstax) | Medium, once |
| Joins that can wait hours | ETL into one warehouse | High, ongoing |
What a cross-database join is, and why it is harder than a normal JOIN
A cross-database join reads rows from tables that live in two or more separate databases and combines them in one query result. Inside one database, the planner sees both tables, their indexes and statistics, and decides how to join them. Across databases, the engine knows little about at least one of the tables. It has to fetch that table’s rows over the network, often without knowing how many there are.
There are three levels of difficulty:
- Same engine, same server. Two MySQL databases on one instance. Usually trivial, because the engine already sees both.
- Same engine, different servers. Two PostgreSQL clusters, or a PostgreSQL database next to another on the same host (PostgreSQL treats them as fully separate). You need an extension that opens a connection to the other side.
- Different engines. MariaDB for the app, PostgreSQL for billing, ClickHouse for events. The engines differ in SQL dialect, type system and wire protocol, so something in the middle has to speak all of them.
Most teams reach level 3 without planning it. One service picked PostgreSQL, analytics moved to ClickHouse, and the legacy core stayed on MariaDB. Then a product manager asks for “revenue by country for users who signed up last month”, and the data for that question sits in three databases.
Method 1: Same server — qualified table names
MySQL and MariaDB. A MySQL “database” is closer to a schema in other engines. If both databases sit on the same instance and your user can read both, prefix the table with the database name:
SELECT u.email, o.total
FROM app.users AS u
JOIN billing.orders AS o ON o.user_id = u.id
WHERE o.created_at >= '2026-10-01';SQL Server. Use three-part names (database.schema.table) on one instance: FROM AppDb.dbo.Users u JOIN BillingDb.dbo.Orders o ON .... For another server you need a linked server and four-part names or OPENQUERY.
PostgreSQL. Qualified names across databases don’t work here. A PostgreSQL connection is bound to one database, so SELECT * FROM otherdb.public.invoices fails with cross-database references are not implemented. If you control the design, the cheapest fix is to move the data into separate schemas of one database instead of separate databases. If you can’t, use one of the extensions in Method 2.
Method 2: PostgreSQL cross-database query with postgres_fdw or dblink
Both ship with PostgreSQL as contrib extensions and work between any two PostgreSQL databases, on the same host or not.
postgres_fdw: remote tables that look local
CREATE EXTENSION postgres_fdw;
CREATE SERVER billing_srv
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'billing-db', port '5432', dbname 'billing');
CREATE USER MAPPING FOR CURRENT_USER
SERVER billing_srv
OPTIONS (user 'reader', password 'secret');
CREATE SCHEMA billing_remote;
IMPORT FOREIGN SCHEMA public LIMIT TO (invoices)
FROM SERVER billing_srv INTO billing_remote;
-- Now it is a normal join
SELECT u.email, i.total
FROM users u
JOIN billing_remote.invoices i ON i.user_id = u.id
WHERE i.paid;postgres_fdw sends WHERE clauses to the remote server when they use built-in, immutable functions, and fetches only the columns the query needs. A join between two foreign tables on the same remote server is pushed down whole. A join between a local and a remote table is not pushed down, so the remote rows are fetched to your server first.
dblink: one remote query, typed by hand
CREATE EXTENSION dblink;
SELECT u.email, i.total
FROM users u
JOIN dblink(
'host=billing-db dbname=billing user=reader password=secret',
'SELECT user_id, total FROM invoices WHERE paid'
) AS i(user_id int, total numeric)
ON i.user_id = u.id;postgres_fdw vs dblink: dblink is fine for a one-off. You write the remote SQL as a string and list the column types yourself. For anything you will run more than once, use postgres_fdw. The planner sees the remote table, filters are pushed down automatically, and you can INSERT or UPDATE through it.
PostgreSQL + MySQL. The same idea works across engines with mysql_fdw, a third-party wrapper maintained by EnterpriseDB. Check first whether your managed PostgreSQL provider allows installing it.
Method 3: ClickHouse table functions mysql() and postgresql()
If your analytics already live in ClickHouse, it can read MySQL and PostgreSQL tables at query time:
SELECT u.country, sum(p.amount) AS revenue
FROM payments AS p
JOIN mysql('mariadb-prod:3306', 'app', 'users', 'reader', 'secret') AS u
ON u.id = p.user_id
WHERE p.created_at >= now() - INTERVAL 30 DAY
GROUP BY u.country
ORDER BY revenue DESC;postgresql('host:5432', 'database', 'table', 'user', 'password') works the same way. Three practical tips:
- In production, store credentials in a named collection instead of query text:
mysql(my_conn, table = 'users'). - ClickHouse’s default hash join keeps the right-hand table in memory. Put the smaller table on the right.
- The remote table is read over the network on every query. If it is large and rarely changes, load it into a dictionary with a MySQL source (cached in memory, refreshed on a schedule) or keep a materialized copy.
Method 4: DuckDB ATTACH for ad-hoc analysis
DuckDB runs inside your laptop, notebook or script, and can attach PostgreSQL and MySQL databases side by side. It is the fastest way to answer a one-off question without touching servers:
INSTALL postgres; LOAD postgres;
INSTALL mysql; LOAD mysql;
ATTACH 'host=billing-db dbname=billing user=reader' AS pg (TYPE postgres, READ_ONLY);
ATTACH 'host=mariadb-prod database=app user=reader' AS my (TYPE mysql, READ_ONLY);
SELECT u.country, sum(i.total) AS revenue
FROM my.users u
JOIN pg.public.invoices i ON i.user_id = u.id
WHERE i.paid
GROUP BY u.country;Filter pushdown is on by default for both extensions. Store passwords in DuckDB secrets instead of the connection string. DuckDB runs as a library inside your process, so your application, BI tool or teammates can’t connect to it, and it does not replace a shared solution.
Method 5: A federated query engine
A federated query is one SQL statement that reads from several independent data sources. The engine that runs it, a federated query engine, keeps a catalog of connected databases, splits the query into per-source parts, pushes filters and aggregations down where it can, pulls back only the needed rows, and does the join itself. The approach is also called data federation or data virtualization. The data stays in the source databases, and the engine presents one SQL view over them.
A federated engine makes sense once cross-database joins are routine: several engines and teams, with queries that run every day from apps, dashboards or AI agents.
Trino (formerly PrestoSQL). Trino is the best-known open-source option. Each source is a catalog (mysql, postgresql, hive…), and you query catalog.schema.table. Trino is a JVM service with a coordinator and workers. Clients connect through Trino’s own JDBC/ODBC drivers or HTTP API, so existing app code needs a new driver and Trino’s SQL dialect. (On Presto vs Trino: Trino is the PrestoSQL fork, renamed in 2020, and both work this way.)
Otterstax. An open-source (Apache 2.0) federation server designed for applications that run cross-database joins, as well as for analysts. It speaks the MySQL/MariaDB and PostgreSQL wire protocols, so an app connects with the driver or ORM it already uses. The open-source version runs as a single process. It can also write (INSERT, UPDATE, DELETE) across MariaDB, PostgreSQL and ClickHouse. Sources include MariaDB/MySQL, PostgreSQL, ClickHouse and S3-compatible storage, with Arrow Flight SQL for data tools and an MCP gateway for AI agents. The next section has a step-by-step example. For a side-by-side comparison, see Otterstax vs Trino.
Method 6: Join in application code, or copy everything with ETL
In application code. Query database A, collect the keys, query database B with WHERE id IN (...), merge in a hash map. It works for small result sets and needs no infrastructure, but it breaks down quickly with pagination and sorting across both sides, N+1 queries, memory use on large sets, and the same glue code copied into every service that needs the join.
ETL / ELT into one warehouse. Replicate every source into one store (with Debezium, Airbyte or similar) and join there. This is still the best choice for heavy historical analytics. It also means the data is minutes to hours old, every new column needs a pipeline change, and you pay to store and maintain a second copy of the data.
Step by step: join MariaDB, PostgreSQL and ClickHouse in one query with Otterstax
This example uses the open-source Otterstax quickstart: a Docker Compose stack with two PostgreSQL databases, one MariaDB, one ClickHouse and S3-compatible storage, all pre-seeded with demo data.
1. Start the stack (about a minute until every container is healthy):
git clone https://github.com/otterstax/otterstax
cd otterstax/examples/quick_start
docker compose up -d
docker compose ps2. See how sources are registered. Every backend is one entry in config.yaml. The alias becomes the first part of the table name in SQL:
connections:
mysql: # MariaDB / MySQL
- alias: sales
host: qs-mariadb
port: "3306"
username: demo
password: demo
database: ops
postgresql:
- alias: pgshop
host: qs-postgres-shop
port: "5432"
username: demo
password: demo
database: shop
schema: shop
clickhouse:
- alias: web
host: qs-clickhouse
port: "9000"
username: demo
password: demo
database: analyticsSo sales.ops.orders is the orders table in MariaDB, pgshop.shop.customers lives in PostgreSQL, and web.analytics.pageviews is in ClickHouse. A second PostgreSQL database is registered the same way under the alias pgcat.
3. Connect with the client you already have. Otterstax listens on the PostgreSQL wire protocol (port 8817) and the MySQL wire protocol (port 8816):
psql -h localhost -p 8817 -U demo demo4. Join two engines. Top customers by paid orders, MariaDB × PostgreSQL:
SELECT c.name, c.country, COUNT(*) AS orders_cnt, SUM(o.amount) AS spend
FROM sales.ops.orders o
JOIN pgshop.shop.customers c ON c.customer_id = o.customer_id
WHERE o.status = 'paid'
GROUP BY c.name, c.country
ORDER BY spend DESC
LIMIT 10;5. Add ClickHouse. Which marketing channel drives paid orders, by product category. Clickstream comes from ClickHouse, orders from MariaDB, and customers and products from two PostgreSQL databases:
SELECT v.channel, p.category,
COUNT(DISTINCT o.order_id) AS orders_cnt,
SUM(o.amount) AS revenue
FROM web.analytics.pageviews v
JOIN sales.ops.orders o ON o.customer_id = v.customer_id
AND o.product_id = v.product_id
JOIN pgshop.shop.customers c ON c.customer_id = o.customer_id
JOIN pgcat.catalog.products p ON p.product_id = o.product_id
WHERE o.status = 'paid'
GROUP BY v.channel, p.category
ORDER BY revenue DESC
LIMIT 10;This statement reads four databases on three engines. Nothing is exported first, and no pipeline or glue code is involved.
6. Point a real app at it. In production you change the connection string. An app that talked to MariaDB keeps its driver and changes one line:
- DATABASE_URL=mysql://app@mariadb-prod:3306/app
+ DATABASE_URL=mysql://app@otterstax:8816/appThe app now sees every registered source through the same connection. More on this setup on the cross-database joins use case page.
Performance: what makes cross-database joins slow, and how to avoid it
With any of these methods, most of the cost of a cross-database join comes from moving rows over the network. These rules apply to all of them.
- Filter at the source. Write filters on columns of the remote table, with plain operators (
=,>,IN), so the engine can push them down. A filter wrapped in a custom function usually can’t be pushed and forces a full remote read. - Select only the columns you need. With
SELECT *, every unused column crosses the network in every row. - Aggregate before you join when you can. Joining 1,000 per-country totals is far cheaper than joining 500 million raw events.
- Watch the intermediate result. Federation slows down sharply when a join pulls hundreds of millions of intermediate rows into the middle layer. Queries like that are better run in a warehouse.
- Match join key types on both sides.
INTvsBIGINT,VARCHARvsTEXT, different collations: mismatches across engines cause slow casts or silently empty results. Cast explicitly, or join on keys of the same type. - Plan for the slowest source. A query across three databases waits for the slowest one. Run analytical joins against read replicas instead of the primary that serves your app.
- Don’t expect one snapshot. There is no shared transaction across engines, so each source is read at a slightly different moment. That is acceptable for reports. Code that moves money has to be designed around it.
A federation layer adds some overhead. For Otterstax, customers measured +10–20% latency on the first run of a query compared with their previous setup (worst case), and +5–10% on repeat runs, thanks to plan and metadata caching, data caching and warm connections. The extra latency comes from the network hop, and in exchange you can remove ETL jobs and per-service glue code.
FAQ
Can you join tables from two different databases?
Yes. On the same MySQL, MariaDB or SQL Server instance, prefix the table with the database name. Across servers or engines, you need a bridge: postgres_fdw or dblink for PostgreSQL, ClickHouse table functions, DuckDB ATTACH, or a federated query engine such as Trino or Otterstax.
Can PostgreSQL query another database?
Not directly: a PostgreSQL session is bound to one database, and otherdb.schema.table returns “cross-database references are not implemented”. Use the postgres_fdw extension for recurring queries, dblink for one-offs, or keep related data in separate schemas of one database.
How do I join MySQL and PostgreSQL tables in one query?
Three options: install mysql_fdw in PostgreSQL and treat MySQL tables as foreign tables; attach both to DuckDB for ad-hoc analysis; or put a federated engine in front of both. With Otterstax, both appear as alias.database.table in one SQL dialect, and your app connects over the MySQL or PostgreSQL protocol.
How do I query multiple databases at once?
If the goal is one combined result (a join or a UNION), you need one engine that can see all the databases, which any method in this guide provides. If you only need to run the same query on many databases separately, a script or your SQL client’s multi-connection feature is enough.
What is a federated query?
A federated query is a single SQL statement that reads data from several independent sources, such as MariaDB, PostgreSQL and ClickHouse, without copying the data into one place first. A federated query engine plans the query, pushes filters to each source, and joins the results.
Is a federated query slower than a normal query?
Somewhat, because every query adds a network hop and waits for the slowest source. With filters pushed down and caching, the overhead is usually small: Otterstax customers measured +5–10% on repeat runs. It gets slow when a join moves hundreds of millions of rows into the federation layer.
Can AI agents run cross-database joins?
Yes, if the agent has one tool that can see every source. Otterstax exposes the same federated SQL to agents through an MCP gateway, so an agent can answer “revenue by country for last month’s signups” with one query instead of calling three database tools and joining in its context window.
Next step
If you join across two or more engines every week, try it on your own stack: the Otterstax quickstart runs locally in about five minutes. To map it onto your production databases, book a 30-minute pilot call.
Sources
More guides
-
What is a federated query engine?
A federated query engine runs one SQL query across several databases without copying data. How it works, how it differs from ETL, and when you need it.
-
Database migration strategies: zero downtime, table by table
Big bang, replica and cutover, dual writes, or table by table through a federated query engine: downtime, rollback and app changes compared, with code.
-
Zero-ETL analytics: when to replace ETL with federated queries
What zero-ETL means, what stays on ETL, what moves to queries on live databases, and how to switch one dashboard at a time without hurting the app.
See Otterstax on your own data sources
In a 30-minute call we'll map your stack and show a working query across your data sources.