A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-foreign-data-wrapper.php below:

Website Navigation


How to Use PostgreSQL Foreign Data Wrappers (FDW) for External Data Access

How to Use PostgreSQL Foreign Data Wrappers (FDW) for External Data AccessLast update on December 23 2024 07:42:06 (UTC/GMT +8 hours)

PostgreSQL Foreign Data Wrapper (FDW)

A Foreign Data Wrapper (FDW) in PostgreSQL is a feature that allows PostgreSQL to access external data stored in different databases, such as another PostgreSQL instance, MySQL, or even files. This enables PostgreSQL to query data from various sources as though it were local, providing seamless integration and data interoperability.

Syntax and Setup for Foreign Data Wrappers:

To use FDWs, you need to:

Example: Setting Up a PostgreSQL FDW to Another PostgreSQL Database

1. Install the postgres_fdw Extension

The postgres_fdw extension enables PostgreSQL to access another PostgreSQL database.

Code:

-- Install the postgres_fdw extension
CREATE EXTENSION IF NOT EXISTS postgres_fdw;

2. Create a Foreign Server

Define the external PostgreSQL database server.

Code:

-- Define the foreign server connection details
CREATE SERVER remote_pg_server
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'remote_host', dbname 'remote_db', port '5432');

Here:

3. Create User Mapping:

Specify the credentials for the user accessing the external database.

Code:

-- Define user mapping for the current user to access the foreign server
CREATE USER MAPPING FOR CURRENT_USER
SERVER remote_pg_server
OPTIONS (user 'remote_user', password 'remote_password');

Here:

4. Create a Foreign Table

Map the external database table to a foreign table in the local PostgreSQL database.

Code:

-- Map a table from the remote database
CREATE FOREIGN TABLE foreign_table (
    id INT,
    name VARCHAR(100),
    age INT
)
SERVER remote_pg_server
OPTIONS (table_name 'remote_table');

Here:

Querying the Foreign Table:

Now, you can query the foreign table as if it were a local table.

Code:

-- Query the foreign table
SELECT * FROM foreign_table WHERE age > 25;

Additional FDW Options:

Explanation of FDW Components:

Summary:

The Foreign Data Wrapper in PostgreSQL offers flexibility for working with multiple data sources by integrating remote databases and external files directly into PostgreSQL. This feature supports distributed queries, data migration, and seamless access to heterogeneous databases.

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4