---
title: "Use dblink to Query Remote Databases"
description: "Query another PostgreSQL database from inside a Managed PostgreSQL service with the dblink extension, or with postgres_fdw."
url: https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-dblink/
product: "PostgreSQL"
section: product
last_updated: 2026-11-10
---
> For AI agents: the documentation index is at https://community.exoscale.com/llms.txt. Every page is available as markdown at `<page URL>index.md` or with `Accept: text/markdown`.

# Use dblink to Query Remote Databases

Connect from inside your Managed PostgreSQL service to another PostgreSQL database, another database of the same service or a remote server, and run queries there with the `dblink` extension.

## Before You Start

- Open a `psql` session as `avnadmin`. See
  [Connect with psql](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/connect-with-psql/index.md).
- Collect the host, port, database name, user and password of the target. For another
  Exoscale Managed PostgreSQL service, or another database of the same service, read them from
  the connection URI:

  ```bash
  exo dbaas show SERVICE_NAME -z ZONE --uri
  ```

  Parameters:

  - `SERVICE_NAME`: name of the service that holds the target database.
  - `ZONE`: zone of that service, for example `ch-gva-2`.

  To reach another database of the same service, use the same host and port and change only
  `dbname`.

> [!IMPORTANT]
> With `dblink`, the database server opens the connection, not your workstation. A remote server
> sees the address of the service, so its firewall must accept that address. Check which address
> it sees with `SELECT inet_client_addr();` run through `dblink` on the remote side, or in the
> remote server's connection log.

## Enable the Extension

In the database you query from:

```sql
CREATE EXTENSION dblink;
```

## Run a One-Off Query

Pass the connection string and the query. Declare the result columns, because PostgreSQL cannot
know the remote row type:

```sql
SELECT *
FROM dblink(
    'host=REMOTE_HOST port=REMOTE_PORT dbname=REMOTE_DATABASE user=REMOTE_USER password=REMOTE_PASSWORD sslmode=require',
    'SELECT item_id, label FROM inventory'
) AS remote_inventory(item_id int, label text);
```

Parameters:

- `REMOTE_HOST`, `REMOTE_PORT`, `REMOTE_DATABASE`, `REMOTE_USER`, `REMOTE_PASSWORD`: connection
  details of the target.

The password is mandatory. Without it, `dblink` stops with
`ERROR: password or GSSAPI delegated credentials required`, because `avnadmin` is not a
superuser. This also applies to another database of the same service: a connection string with
only `dbname=OTHER_DB` fails the same way.

> [!WARNING]
> A connection string written in a query can end up in `pg_stat_activity`,
> `pg_stat_statements` and the service logs. For anything recurring, store the credentials in a
> user mapping, see [Store Credentials in a User Mapping](#store-credentials-in-a-user-mapping).

## Use a Named Connection

To run several queries against the same target, open a named connection once:

```sql
SELECT dblink_connect(
    'inventory_conn',
    'host=REMOTE_HOST port=REMOTE_PORT dbname=REMOTE_DATABASE user=REMOTE_USER password=REMOTE_PASSWORD sslmode=require'
);
```

```sql
SELECT *
FROM dblink('inventory_conn', 'SELECT item_id, label FROM inventory')
    AS remote_inventory(item_id int, label text);
```

Run a statement that returns no rows, such as `UPDATE` or `DELETE`, with `dblink_exec()`:

```sql
SELECT dblink_exec('inventory_conn', 'DELETE FROM inventory WHERE archived');
```

List the open connections of the session, then close the connection:

```sql
SELECT unnest(dblink_get_connections());
```

```sql
SELECT dblink_disconnect('inventory_conn');
```

> [!CAUTION]
> A named connection belongs to the server session. Through a connection pool in `transaction`
> mode, consecutive statements can run on different server sessions, so the connection may be
> missing, or left open for another client. Use the PostgreSQL port of the service for work that
> relies on `dblink_connect()`. See
> [Manage connection pools](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-connection-pools/index.md).

## Store Credentials in a User Mapping

Define the target once as a foreign server, attach the credentials to a user mapping, then use
the server name instead of a connection string:

```sql
CREATE SERVER inventory_srv
    FOREIGN DATA WRAPPER dblink_fdw
    OPTIONS (
        host 'REMOTE_HOST',
        port 'REMOTE_PORT',
        dbname 'REMOTE_DATABASE',
        sslmode 'require'
    );
```

```sql
CREATE USER MAPPING FOR avnadmin
    SERVER inventory_srv
    OPTIONS (
        user 'REMOTE_USER',
        password 'REMOTE_PASSWORD'
    );
```

```sql
SELECT *
FROM dblink('inventory_srv', 'SELECT item_id, label FROM inventory')
    AS remote_inventory(item_id int, label text);
```

The server name also works with `dblink_connect('inventory_conn', 'inventory_srv')`.

To let another role use the server, grant it `USAGE` and create a mapping for it:

```sql
GRANT USAGE ON FOREIGN SERVER inventory_srv TO USERNAME;
```

```sql
CREATE USER MAPPING FOR USERNAME
    SERVER inventory_srv
    OPTIONS (
        user 'REMOTE_USER',
        password 'REMOTE_PASSWORD'
    );
```

Parameters:

- `USERNAME`: a role of this service. Without its own mapping, it gets
  `ERROR: user mapping not found for user "USERNAME", server "inventory_srv"`.

## Security Considerations

- **Who can call dblink.** The `dblink` functions are owned by the platform and executable by
  every role of the database. `avnadmin` cannot revoke that (`REVOKE` reports
  `no privileges could be revoked`). Create the extension only in the databases that need it.
- **Stored passwords.** `avnadmin` can read the options of its own user mappings, password
  included, in `pg_user_mappings`. Other roles do not see the options of the mappings of
  `avnadmin`. Use a dedicated, least-privileged account on the remote side.
- **Certificate checks.** `sslmode=require` encrypts the connection but does not check the
  remote certificate. For a server outside your control, use `sslmode=verify-full` with an
  `sslrootcert` option.

## Use postgres_fdw Instead

`postgres_fdw` maps remote tables into the local catalog. The planner can then send filters,
joins and aggregates to the remote server, and you write ordinary queries without declaring
result types.

|  | `dblink` | `postgres_fdw` |
| --- | --- | --- |
| Remote objects | Queries passed as text | Foreign tables |
| Result types | Declared in every call | Imported once |
| Planner | Remote query is opaque | Filters, joins and aggregates can run remotely |
| Writes | `dblink_exec()` | `INSERT`, `UPDATE`, `DELETE` |
| Good for | One-off queries, dynamic SQL | A standing link to a remote schema |

Setup uses the same foreign server and user mapping model:

```sql
CREATE EXTENSION postgres_fdw;
```

```sql
CREATE SERVER inventory_fdw
    FOREIGN DATA WRAPPER postgres_fdw
    OPTIONS (
        host 'REMOTE_HOST',
        port 'REMOTE_PORT',
        dbname 'REMOTE_DATABASE',
        sslmode 'require'
    );
```

```sql
CREATE USER MAPPING FOR avnadmin
    SERVER inventory_fdw
    OPTIONS (
        user 'REMOTE_USER',
        password 'REMOTE_PASSWORD'
    );
```

Import remote tables into a local schema, then query them:

```sql
CREATE SCHEMA remote_inventory;
```

```sql
IMPORT FOREIGN SCHEMA public
    LIMIT TO (inventory, warehouses)
    FROM SERVER inventory_fdw
    INTO remote_inventory;
```

```sql
SELECT w.name, count(*) AS items
FROM remote_inventory.inventory i
JOIN remote_inventory.warehouses w ON w.id = i.warehouse_id
GROUP BY w.name;
```

Check what runs remotely:

```sql
EXPLAIN (VERBOSE)
SELECT count(*) FROM remote_inventory.inventory WHERE archived;
```

The plan shows a `Foreign Scan` whose `Remote SQL` line contains the `WHERE` clause and the
`count(*)`, which means both run on the remote server.

## Related Pages

- [Manage extensions](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-extensions/index.md)
- [Manage connection pools](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-connection-pools/index.md)
- [Restrict connections to a service](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/restrict-connections/index.md)
- [Use aiven_extras for superuser operations](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/use-aiven-extras/index.md)
- [dblink in the PostgreSQL documentation](https://www.postgresql.org/docs/current/dblink.html) ↗
- [postgres_fdw in the PostgreSQL documentation](https://www.postgresql.org/docs/current/postgres-fdw.html) ↗

