Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a foreign table with only specific columns

I would like to know if there is a way to create a foreign table only with specific columns and conditions in PostgreSQL. For example i saw someone suggest this command but it doesn’t really work because the OPTIONS (table '') at the bottom doesn’t actually exist.

CREATE FOREIGN TABLE app_users (
id INT NOT NULL,
login VARCHAR(190),
email VARCHAR(190),
"name" VARCHAR(255)
) SERVER fdw_app
OPTIONS (
table '(SELECT id, login, email, "name" FROM public."user" WHERE login like ''app-%'')');

Sql returns that the available options are only schema_name, table_name, use_remote_estimate, updatable, fetch_size

Is there an actual way to do this or is it impossible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re correct that the syntax you provided is not valid in PostgreSQL, as it doesn’t support specifying a query for a foreign table directly in the CREATE FOREIGN TABLE statement.

However, you can achieve a similar result by creating a view on the foreign server side that filters the data as desired, and then create a foreign table in your local PostgreSQL server to access that view.

  1. Connect to the remote server and create a view:
CREATE VIEW public.filtered_users AS
SELECT id, login, email, "name"
FROM public."user"
WHERE login LIKE 'app-%';
  1. In your local PostgreSQL server, create a foreign table to access the remote view:
CREATE FOREIGN TABLE app_users (
  id INT NOT NULL,
  login VARCHAR(190),
  email VARCHAR(190),
  "name" VARCHAR(255)
) SERVER fdw_app
OPTIONS (
  schema_name 'public',
  table_name 'filtered_users'
);

With these steps, you’ll have a foreign table named app_users in your local PostgreSQL server, which corresponds to the filtered view in the remote server. You can then query app_users as if it were a local table. Note that this approach requires you to have access to the remote server to create the view.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading