Querying remote PostgreSQL databases with postgres_fdw

postgres_fdw lets one PostgreSQL server query tables on another through foreign tables, but credential storage, pushdown limits and network coupling decide whether it fits. This page covers when to use it and how to set it up safely.

On this page

When postgres_fdw is the right way to query a remote PostgreSQL database

A team needs to join or report on data that lives on another PostgreSQL server, and the first decision is whether a foreign data wrapper is the right tool at all. The postgres_fdw module is PostgreSQL's foreign-data wrapper for reaching tables held in external PostgreSQL servers. As the official postgres_fdw documentation describes it, you define a foreign server, map local roles to remote logins, and expose remote tables locally as foreign tables that you query with ordinary SQL. The local server sends the remote parts of a query to the remote server, so a join between a local table and a remote table runs with the remote data pulled in on demand rather than copied in advance.

The older dblink module covers much of the same ground. Both let a session on one server read from another server, and the PostgreSQL documentation notes that their functionality overlaps substantially. The practical difference is the interface. postgres_fdw gives you foreign tables that planners can reason about, so filters and joins can be pushed down to the remote side and the result feels like a local table to applications and reporting tools. dblink returns results from explicit function calls and leaves the remote query as text your code assembles. For recurring reporting or joins that many queries share, foreign tables are usually easier to review and maintain.

postgres_fdw fits best for occasional or moderate-volume cross-database reads, such as a reporting server that needs a few reference tables from an operational database, a consolidation view over a small number of sites, or a one-off reconciliation. It is a weaker fit for large scans that move much of a remote table across the network, for workloads that need a local copy that stays up when the remote server is down, and for anything that writes across servers without careful design. Before committing, confirm the network path, the remote server's load tolerance and how many remote rows a typical query touches, and test the most important queries with EXPLAIN to see what actually runs remotely.

Configuration options and when each fits

This table compares the postgres_fdw objects and server options you will set up, what each one controls, and the trade-off it carries. Read it as a checklist: pick the object or option that matches the query pattern, then confirm the behavior against the postgres_fdw documentation for your PostgreSQL version before relying on it.

Object or optionWhat it controlsWhen it fitsTrade-off to weigh
Foreign server (host, port, dbname)Where the remote PostgreSQL database is and which database on it is reachedOne named entry per remote database, so every foreign table points at a clear targetEach server object is a network path to plan, monitor and firewall, and a change to the host needs updating in every dependent definition
User mappingWhich local role connects remotely and with which remote loginSeparate remote logins per local role, so the remote side can enforce its own privilegesPasswords are stored in the catalog, so the mapping needs tight privileges and a credential rotation process
Foreign table definitionThe local name, columns and types that map to a remote table or viewNarrow, deliberate exposure of specific remote tables or views to local queriesColumn drift on the remote side can break queries silently until someone checks the definition
IMPORT FOREIGN SCHEMABulk creation of foreign table definitions from a remote schemaFast setup when the remote schema is stable and you want most of its tablesImports everything matched by the filter, which can expose more than intended; review the result before granting access
fetch_sizeHow many rows are retrieved from the remote server per round tripLarge result sets where per-row round trips would dominate runtimeLarger batches use more local memory per fetch, so size it against your concurrent query load
use_remote_estimateWhether the planner asks the remote server for row estimatesJoins or filters where local guesses produce poor plansEach planning step adds a remote round trip, which costs time on short queries
extensionsWhich remote extensions are known to the planner for pushdown decisionsRemote queries that rely on an extension function you want pushed to the remote serverListing an extension the remote side does not have can produce failed or incorrect remote queries; confirm it in the docs first
Pushdown of WHERE clauses and joinsWhether filters and joins execute on the remote server instead of locallySelective filters and joins between tables on the same remote serverOnly operations the wrapper can translate are pushed; check the EXPLAIN output to see what actually ran remotely

How remote query pushdown decides what runs where

postgres_fdw sends as much of a query to the remote server as it can safely express, and fetches the rest to run locally. Conditions that can be evaluated on the remote side, such as a WHERE clause on a column of the foreign table, can be included in the remote query, so the remote server filters rows before they cross the network. Joins between foreign tables on the same remote server and certain aggregates can also be sent as a single remote query when the foreign server and user mapping allow it. Anything the local planner cannot push, such as a function or operator that does not exist on the remote side, is applied locally after rows are fetched. The practical consequence is that the same SQL can run very differently depending on which expressions are eligible, so the design question is which filters and joins your application depends on, not whether the foreign table "works."

Plan quality depends heavily on statistics. The local planner estimates how many rows a remote scan will return and chooses join order and join method from those estimates, but it does not hold the remote table's statistics unless you collect them locally through ANALYZE on the foreign table. Where estimates are poor, the planner may choose a local join strategy that pulls large result sets across the network. Before you rely on a given pushdown, run EXPLAIN VERBOSE on the query and read the Remote SQL line under each foreign scan. It shows the exact statement sent to the remote server. Confirm that the filter and join conditions appear there. Then check the row estimates against the remote table's actual size. Run the same check against a staging copy of the remote database, because production data volumes change the plan.

Pushdown behavior is tied to the PostgreSQL major version on both the local and the remote server, and the postgres_fdw release notes for your version are the authority on what is pushed in your environment. Do not assume a pushdown carries over from an example you read or from a different version. Confirm it for each local and remote version pair you run, record the EXPLAIN VERBOSE output as a baseline, and repeat the check after any major upgrade of either server. Supported versions and their end-of-life dates are listed in the PostgreSQL versioning policy, which helps you plan those upgrades before a pushdown changes under a live workload.

How to set up a foreign server, user mapping and foreign table

This sequence takes a PostgreSQL database from no remote connection to a tested foreign table that queries another PostgreSQL server with bounded, reviewable access. Each step ends with a check so that a failure is caught before the next layer of access is added.

  1. Install the postgres_fdw extension

    A database administrator connects to the local database that will hold the foreign table and runs CREATE EXTENSION postgres_fdw as a role allowed to create extensions. The module is distributed with PostgreSQL, but the package containing it must be present on the local server, so confirm the extension is available in your installed packages before you start. Check the result by querying pg_extension for postgres_fdw in the database; the row confirms the wrapper can now be used there, and the same step should be repeated in every database that needs remote access.

  2. Create the foreign server object

    Using CREATE SERVER with the FOREIGN DATA WRAPPER postgres_fdw clause, the administrator names the remote host, port and database the local server will connect to. Connection options should point at a stable internal address and, where your security policy requires it, the TLS settings you plan to enforce, rather than a developer workstation or a changing IP. Check the object by listing pg_foreign_server; it confirms the definition exists but does not prove the remote server is reachable, so that is tested in the later query step.

  3. Create a dedicated remote role with least privilege

    On the remote server, a database administrator creates a login role used only for these queries, with no superuser, no create-database rights and no ownership of the tables it reads. The role receives CONNECT on the target database, USAGE on the schema, and SELECT only on the specific tables or views the local side needs, ideally exposed through views that omit sensitive columns. Confirm the grants by connecting as that role and attempting one allowed read and one disallowed read; the allowed read should succeed and the other should be refused.

  4. Create the user mapping

    The local administrator runs CREATE USER MAPPING for the local role that will query remotely, pointing it at the server object and the remote role's name and password. Because the password is stored in the local catalog, the mapping should be created by a role with restricted access, and the remote login should use a password that rotates under your credential policy. Verify the mapping by listing pg_user_mappings and then running a trivial query through a session as the local role; if authentication fails, the error identifies the mapping or remote authentication step that needs correction.

  5. Define or import the foreign tables

    The administrator either declares each foreign table manually with CREATE FOREIGN TABLE, listing column names and types that match the remote definition, or uses IMPORT FOREIGN SCHEMA with a LIMIT TO clause to bring in only the approved relations. Importing the whole schema is usually a mistake, because it exposes objects nobody reviewed. Check the result by describing each foreign table with the psql meta-command and comparing the column list with the remote table, since a type mismatch will show up only when a query touches that column.

  6. Run a bounded test query

    A tester runs a SELECT against the foreign table with a WHERE clause on an indexed remote column and a LIMIT, so the first test cannot pull a large result set across the network. The expected result is a small set of rows matching the filter, returned without an authentication or permission error. If the query returns an error about the role, the remote grants from the third step are incomplete; if it hangs, the network path or firewall rule between the two servers needs review before any further testing.

  7. Confirm the plan shape with EXPLAIN

    The tester runs EXPLAIN VERBOSE on the same bounded query and reads the Foreign Scan node to see which conditions and limits were sent to the remote server in the generated remote SQL. The plan should show the filter and the limit applied remotely; if the whole table appears to be transferred and filtered locally, the query shape or column types are preventing pushdown and the query should be rewritten before it is used by an application. Record the plan output with the change ticket, because it is the baseline you will compare against after remote schema or version changes.

How to protect credentials stored in user mappings

A foreign server is only as safe as the credentials behind it. The cards below cover where postgres_fdw keeps passwords, which remote role it should use, how the remote server admits the connection, who may create the links in the first place, and how to see what crosses them.

Restrict who can read the catalog

Passwords supplied in a user mapping are stored in the local catalog, so anyone who can read that catalog data may be able to recover them. Limit access to the catalog view that exposes mapping options, and check which roles hold broad read rights. Confirm the exact visibility rules for your PostgreSQL version in the postgres_fdw documentation before you rely on them.

postgres_fdw docs

Use a least-privilege remote role

Create a dedicated login role on the remote server that can read only the tables and columns the query needs. Do not map local administrators or the owner of the remote schema, because a leaked mapping would then grant write and DDL rights. Grant SELECT on specific objects and review the role whenever a new join is added.

Restrict remote access in pg_hba.conf

On the remote side, pg_hba.conf decides which hosts, databases and users may connect and how they must authenticate. Allow only the local application server address for the FDW role, and require a method such as SCRAM password authentication or certificates rather than trust or MD5. Authentication method options are listed in the PostgreSQL client authentication documentation.

Authentication methods docs

Encrypt the connection with TLS

Without TLS, the mapped password and the returned rows travel over the network in a form that can be observed by anyone with access to the path. Set the connection options so the client requires an encrypted session, and verify the server certificate when the platform supports it. Confirm the exact option names and certificate checks for your installed version and client library.

Control who can create servers and mappings

Creating a foreign server or user mapping is a privilege that reaches into another database, so it should not be granted casually. Decide which roles may run CREATE SERVER and CREATE USER MAPPING, keep those rights out of application roles, and record every new link as a reviewed change. Confirm the privilege model for USAGE on foreign servers in the current documentation.

Audit remote access

Logs on the remote server show which role connected and from which address, and they should be reviewed for sessions the application never expected. Enable connection and statement logging at a level your team can afford to store, and alert on logins from unexpected hosts or on the FDW role issuing writes. Confirm the logging parameters for your version and retention needs before go-live.

When replication is the better design than a foreign table

postgres_fdw suits occasional, bounded reads, and replication suits anything that must keep running when the other server is busy or slow. A foreign table sends each query to the source server at the moment it runs, so the source takes the load, its availability becomes part of your query path, and its latency lands on every join. Before you adopt a foreign table, ask who owns the source, how often reporting will query it, and whether a dashboard refresh could stall a transactional workload that the source is already serving.

Streaming replication with a hot standby is the first alternative to test. A hot standby serves read-only queries, so reporting can run against a copy of the whole cluster without touching the primary's workload, and synchronous or asynchronous replication sets how far that copy may trail. Logical replication is the better fit when you need only selected tables, when the target runs a different PostgreSQL major version, or when the consumer is a separate site with its own schema. It copies row changes rather than the physical cluster, so confirm with the PostgreSQL high availability documentation which features each approach supports before you commit to a design.

Periodic extracts remain sound when the business accepts data that is hours or days old and the reporting logic is simple. Keep the source decoupled, with an extract that a scheduled job writes into a local table, and treat the freshness target as a requirement to write down. The decision comes down to three questions: how fresh must the data be, how much load can the source absorb, and what happens to your reports if the source is down. If the honest answers are current, unlimited and unaffected, replication or a copied table is the safer design, and a foreign table belongs to the cases where the query is rare and the source owner has agreed to it.

Questions teams ask before querying remote databases

How much effort does a postgres_fdw setup take?

Effort depends mostly on how many remote servers and tables are involved, how many distinct roles need access, and how much of the query workload must run on the remote side. A single read-only foreign table to one server is a small job. A set of joins across several servers, each with its own network path, role model and test queries, is a larger one. The setup itself is a few catalog objects (a foreign server, user mappings, foreign tables), so most of the time goes to access design, network approval and verifying that queries push down as expected. Ask any partner to size the work from a written list of servers, tables, roles and query samples.

What drives the cost of this work, and what recurs afterward?

Cost follows the number of servers, the complexity of the joins and the number of environments that need the same definitions (development, staging, production). The one-time parts are design, implementation, testing and handover. Recurring parts are changes when remote schemas evolve, PostgreSQL version upgrades on either side, and periodic review of who holds access. Ask for a quote that lists these items separately, names who performs each task and states what is excluded, such as changes to the remote databases themselves.

Can our internal team set up postgres_fdw without outside help?

Yes, a team with solid PostgreSQL administration skills can configure foreign servers and user mappings on its own, since the module is part of the PostgreSQL distribution and the configuration is documented. The harder parts are usually organizational: agreeing on which tables may cross the boundary, getting network rules approved between database hosts, and reviewing role privileges so the remote account stays narrow. An outside partner adds most value when the design spans several teams or environments, or when your security reviewers need written evidence of the access model.

What do we need to provide before the work starts?

Plan to provide network paths and firewall change approvals between the local and remote hosts, PostgreSQL versions and extension availability on both sides, and a named owner for each remote database. You will also need a dedicated remote role for each access pattern, a list of tables and columns that may be read, and realistic query samples with row counts, so the pushdown behavior can be checked. Access to a test copy of the remote data helps verification. Confirm each item in your own environment before the schedule is set.

How should credentials for remote servers be stored and rotated?

Store the remote password in a user mapping, which lives in the local catalog, so the database owner and superusers can read it. Limit access to the catalog, use a remote role with only SELECT on the approved objects, and avoid reusing an application password. Require TLS for the connection, and confirm which authentication method the remote server accepts for that role. Rotation means updating the user mapping and checking that no other system reuses the credential. Your secrets policy should decide whether the password is stored at all or whether a shorter-lived mechanism is used. Confirm the approach with your security team before deployment.

Does postgres_fdw affect the security of the remote database?

It can. Every query through a foreign table runs as the remote role mapped to the local user, so a broad remote role exposes everything that role can read to anyone who can query the foreign table. Restrict remote privileges to specific schemas, tables and columns, and avoid owner or privileged roles. Review the remote audit trail to confirm which queries arrive and from which local host. Row-level policies on the remote side will also apply to the mapped role, which is a useful control when the design requires it.

When should we use logical or streaming replication instead?

Choose replication when the remote data must be available locally at all times, when reports join very large tables and repeated remote reads add load, or when a remote outage would stop the business function that needs the data. The PostgreSQL high availability documentation describes the standby and replication options. Foreign data wrappers suit occasional cross-database queries, ad hoc reporting and migration aids. Replication suits steady copies with predictable latency. Many designs combine both, with a replica for reads and a foreign table for small reference lookups.

How do we verify that queries are pushed down to the remote server?

Run EXPLAIN VERBOSE on representative queries and check whether filters, joins and aggregates appear in the remote SQL shown for the foreign scan. Compare row counts and run times against the same query on a local copy. Set use_remote_estimate where planner estimates matter, and test with analyze on the foreign tables. Pushdown depends on the operators and functions involved, so keep a written list of queries that must push down and rerun it after each remote schema change or PostgreSQL upgrade.

How the local server reaches remote tables through postgres_fdw

A query starts on the local server against a foreign table, which points to a foreign server definition and a user mapping that supplies the login used on the remote side. The local planner decides which filters and joins can be sent to the remote server and which must run locally, then the connection carries that work across. Check which role the stored credential belongs to, and which parts of the plan actually reach the remote server.

Request flow from a local query through foreign objects to the remote database.

How DeployOpen scopes and delivers postgres_fdw integrations

DeployOpen approaches cross-server queries with postgres_fdw as a scoped build inside your own infrastructure, starting with the questions about which data must be read live and which should be replicated. We agree the scope, the test plan and the handover in writing before the work starts, so your team can review each decision.

How we scope

  • Inventory which remote tables, views and queries need live access and how often they run
  • Define the foreign server, user mapping and role model for each source database in writing
  • Decide with you whether replication, a read replica or a reporting copy fits better than live foreign tables

How we build

  • Create foreign servers and user mappings in a controlled order, with credentials stored outside plain SQL scripts
  • Check pushdown of filters, joins and aggregates with EXPLAIN on realistic data volumes before approving queries
  • Test network paths, TLS settings and failure behavior when the remote server is slow or unavailable

How we hand over

  • Deliver a written design record covering servers, mappings, grants, pushdown findings and known limits
  • Provide runbooks for credential rotation, adding a remote source and diagnosing slow foreign queries
  • Walk your database and security teams through the configuration and the retest results

How we support

  • Support is available as a retainer for changes to remote sources, PostgreSQL upgrades and periodic access reviews
  • Retesting after upgrades of the local or remote PostgreSQL server can be included in the retainer scope
  • Ask any provider to confirm in writing who owns credential rotation and monitoring after handover

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.