matt b matt b - 5 months ago 72
SQL Question

Possible to perform cross-database queries with postgres?

I'm going to guess that the answer is no based on the below error message (and this Google result), but is there anyway to perform a cross-database query using Postgres?

databaseA=# select * from databaseB.public.someTableName;
ERROR: cross-database references are not implemented:
"databaseB.public.someTableName"


I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the
users
table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie...

Answer

Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two schemas instead - in that case you don't need anything special to query across them.

Update as of 9.3

You can now use the new postgres_fdw (foreign data wrapper) to connect to tables in any Postgres database - local or remote.

Note that there are foreign data wrappers for other popular data sources. At this time, only postgres_fdw and file_fdw are part of the official Postgres distribution.

Original answer for pre-9.3

This functionality isn't part of the default PostgreSQL install, but you can add it in. It's called dblink.

I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib.

Comments